Watchers in Vue.js

Watcher in Vue.js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue.js instance. Watchers are the most useful when used to perform asynchronous operations.

Watchers in Vue.js observe reactive properties and can detect when a property changes. It essentially acts as an event listener for our component’s reactive data.

Especially when combined with asynchronous API calls, there are hundreds of use cases like

  • Getting an object from database when an ID changes
  • Rerunning an animation when a prop changes
  • So many more!

Example:

<template>
<div>
<input type="number" v-model="value" placeholder="Enter Number" class="form-control"/>
Number Multiply By 2= {{result}}
</div>
</template>

 

export default{
  data : function(){
      return{
          value:'',
          result:0
       };
   },
   watch:{
     value : function(val){
        this.value=val;
        this.result=2 * val;
     },
     result : function (val) { 
        this.result = val; 
     } 
  }
}

The Watcher now looks for changes in the input value. Whenever the input value changes, the function inside is automatically executed (that multiplies input value by 2), and the value of result changes automatically.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories