Dynamic Reactive Styles and Classes
Explore how to bind styles and classes reactively to DOM elements based on the component's state.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Reactive Styles</title>
<style>
.dynamic-color {
background-color: #fff;
}
</style>
</head>
<body>
<div id="app">
<button id="changeColor">Change Color</button>
<div id="box" class="dynamic-color" style="width: 100px; height: 100px;"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
isActive: true,
activeColor: 'red',
fontSize: 30
},
methods: {
changeColor: function () {
this.isActive = !this.isActive;
}
},
computed: {
dynamicStyle: function () {
return {
backgroundColor: this.isActive ? this.activeColor : '#fff',
fontSize: this.fontSize + 'px'
};
}
}
});
// Event listener for color change
document.getElementById('changeColor').addEventListener('click', function() {
app.changeColor();
});
</script>
</body>
</html>
This HTML page includes an example of dynamic reactive styles using Vue.js. There is a button to trigger a color change and a div element whose background color and font size will change reactively based on the component's state. Vue.js is used to toggle the isActive state and compute the dynamicStyle based on this state.