Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue.js Watch Properties

Vue.js Watch Properties

In this chapter we introduce the Vue.js watch property; 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('Counter value changed :' + oval + ' changed to ' + nval + '!'); });

script

Try it »

The following example performskilometersThe difference betweenmetersconversion between:

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 invoked after vm.kilometers changes document.getElementById ("info").innerHTML = "Value before change: " + oldValue + ", value after change: " + newValue; })

script

Try it »

Click the "Try it" button to view the online example

In the code above, we created two input boxes. In the data property, kilometers and meters both start with an initial value of 0. The watch object creates two watcher methods for the data object: kilometers and meters.

When we enter data in the input boxes, watch listens to the data changes in real time and updates its own value. You can see the video demonstration below: