Vue.js Watch Properties
In this chapter, we will introduce Vue.js watch properties. We can use watch to respond to data changes.
The following example implements a counter using watch:
Example
<div id = "app">
<p style = "font-size:25px;">Counter: {{ counter }}</p>
<button @click = "counter++" style = "font-size:25px;">Click me</button>
</div>
<script type = "text/javascript">var vm = new Vue({
el: '#app',
data: {
counter: 1
}
});
vm.$watch('counter', function(nval, oval) {
alert('The counter value changed from ' + oval + ' to ' + nval + '!');
});</script>
Try it Yourself »
The following example performs the conversion betweenkilometersandRiceand meters:
Example
<div id = "computed_props">Kilometers :<input type = "text" v-model = "kilometers">Meters :<input type = "text" v-model = "meters">
</div>
<p id="info"></p>
<script type = "text/javascript">var vm = new Vue({
el: '#computed_props',
data: {
kilometers : 0,
meters:0
},
methods: {
},
computed :{
},
watch : {
kilometers:function(val) {
this.kilometers = val;
this.meters = this.kilometers * 1000
},
meters : function (val) {
this.kilometers = val/ 1000;
this.meters = val;
}
}
});
// $watch is an instance method
vm.$watch('kilometers', function (newValue, oldValue) {
// This callback will be called after vm.kilometers changes
document.getElementById ("info").innerHTML = "Value before modification: " + oldValue + ", value after modification: " + newValue;
})</script>
Try it Yourself »
Click the "Try it Yourself" button to view the online example
In the above code, we created two input boxes. In the data property, the initial values of both kilometers and meters are 0. The watch object creates two monitoring methods for the data object: kilometers and meters.
When we enter data in the input boxes, watch monitors data changes in real time and changes its own value. You can watch the following video demonstration:
Other Extensions