Vue Watcher | When Would You Use a Watcher?

Have you ever been used vue js watch property? If you are not, then you are a right place. In this tutorial i will discuss about vue js watch property and we will compare it with computed property.

When we have some data that needs to change based on some other data, it is tempting to overuse watch. When computed properties are more appropriate in many cases, there are sometimes when a custom watcher is necessary.

For this reason Vue provides a more generic way to react to data changes through the watch option. This is most useful when you want to perform asynchronous or expensive operations in response to changing data in vue js.

You should know that computed properties are cached based on their reactive dependencies.  A computed property will only re-evaluate when some of its reactive dependencies have changed.

In this vue watch object property example i will create a simple vue example. We will create three text field containing km, meter and millimeter. When one field is changed then all the field data will be updated according to their corresponding value.

See the below example:

 

JavaScript - Vue js

new Vue({
    el: '#app',
    data: {
    	km2: 0,
        cm: 0,
        mm: 0
    },
    watch: {
        km2: function(val){
            this.km2 = val;
            this.cm = val * 100000;
            this.mm = val * 1000000;
        },
        cm: function(val){
            this.km2 = val / 100000;
            this.cm = val;
            this.mm = val * 10;
        },
        mm: function(val){
            this.km2 = val / 1000000;
            this.cm = val / 10;
            this.mm = val;
        },
    }
});

 

Read also : Don’t Use v-if with v-for Elements

 

Hope this vue js watch property tutorial will help you.