Vue.js Watcher Properties
In this section, we will introduce the Vue.js watcher property, watch
, which allows us to respond to data changes.
The following example demonstrates 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('Counter value changed from: ' + oval + ' to ' + nval + '!');
});
</script>
The following example performs conversion between kilometers and 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 change: " + oldValue + ", Value after change: " + newValue;
});
</script>
Click the "Try It" button to see the live example.
In the above code, we created two input fields with kilometers
and meters
initialized to 0 in the data
property. The watch
object creates two monitoring methods for the data
object: kilometers
and meters
.
When we enter data into the input fields, watch
listens for real-time changes and updates the values accordingly. You can see a demonstration in the following video: