VueJs Watch

It is most useful when you want to perform asynchronous or expensive operations in response to changing data. Keep in mind watchers only change when that specific data property changes.

In this topic, we'll learn about the Watch property. Below the example, we'll see we can use it.

<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
     <div id="watch">
	     <input type="text" v-model="meter" placeholder="meter" />
	     <input type="text" v-model="cm" placeholder="cm" />
     </div>
     <script>
     new Vue ({
        	el: '#watch',
		data: {
		          meter : '',
			  cm : '',
		       },
		 methods : {
			   },
		 watch: {
			  meter: function(val)
				  {
				        this.meter = val;
					this.cm = val * 100;
				  }, 
			  cm: function(val)
				   {
				          this.meter = val / 100;
					  this.cm = val;
				   }
			}	   
	})
   </script>
 </body>
</html>

Above, we've created two textboxes, one for meter and second for centimeters. In data property, the meter and cm are initialized to empty. There is a watch object created with two functions meter and cm. In both the functions, the conversion from meter to cm and vice-versa.

We enter values inside any of the texboxes, whichever is changed, Watch takes care of updating both the textboxes. We don't have to specially assign any events and wait for it to change and do the extra work of validating. Watch takes care of updating the textboxes with the calculation done in the respective functions.

Output