Vue.js is a very impressive and reactive JavaScript’s front-end framework used to develop front-end websites quickly and easily. This post will learn about the watch property that is one of the most fundamental concepts.
Vue.js provides a watch property to watch a variable, and on the change of that variable, it allows us to run a function so that we can make Dynamic Interaction. Let’s try an example and have some dynamic interaction using the Vue Watch property.
Example
We will first try to change some variable at the click of a button, and then using the watch property, we will watch that variable and alter some other variable to make the dynamic changes on the web page.
data() {
return {
buttonBool: true,
color: "red"
}
}
And we have bound the “buttonBool” variable with a button element in the template.
<div class="test">
<h1>This is a testing page</h1>
<button @click="buttonBool=!buttonBool">Click me!</button>
</div>
</template>
We want to change the background color of a, let’s say, a division at the click of the button. So, first, create a div in the template.
Now, let’s first create a watch property and change the state of the “color” variable at the change of the “buttonBool” variable.
buttonBool(){
this.color = !this.color;
}
}
Alright! The last step left is to change the classes of the div on the change of color variable. So, let’s do that by using the class binding feature of Vue.js.
<div class="test">
<h1>This is a testing page</h1>
<button @click="buttonBool=!buttonBool">Click me!</button>
<div :class="[color ? 'red' : 'green', 'box']"></div>
</div>
</template>
Here, I have just assigned the class “red” if the state of the “color” variable is true, else “green” if the state of the color variable is “false,” and the “box” class is assigned in any case.
The CSS for giving the width, height, and background color to the div is as follows.
.box{
width: 100px;
height: 100px;
margin: 15px auto;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
Alright, after getting done with the coding stuff, my web page would be like this.
Now, whenever I click the button, the background color of the box should get changed.
And you can witness in the gif above, the color of the div is changing at the click of the button. That’s amazing, right!
So, this is how we can use the Vue Watch to make dynamic interaction on the webpage.
Conclusion
In this post, we have tried to change some variable’s state at the click or change of some other variable using the watch property of Vue.js. We have also made some dynamic changes to the web page. We have seen that at the click of the button, in the on-click attribute, we changed the variable’s state and shown that the watch property watched the variable and performed some action like changing some other variable’s state.