Loading, please wait...

A to Z Full Forms and Acronyms

How to work with VueJs Watch Properties | VueJs Tutorials

In This Article, we'll learn how to work with VueJs Watch Properties, and a brief explanation with appropriate examples.

VeuJs Watch Property

Vue gives a more general approach to observe and respond to data changes on a Vue instance: watch properties. At the point when you have some data that needs to be changed based on some other data, it is enticing to overuse watch particularly when you are coming from an AngularJS background.

Using an example, we will see we can use the Watch property in VueJS:

Example

<html>
   <head>
      <title>VueJs Instance</title>
      <script type = "text/javascript" src = "js/vue.js"></script>
   </head>
   <body>
      <div id = "computed_props">
         Kilometers : <input type = "text" v-model = "kilometers">
         Meters : <input type = "text" v-model = "meters">
      </div>
      <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 = val * 1000;
               },
               meters : function (val) {
                  this.kilometers = val/ 1000;
                  this.meters = val;
               }
            }
         });
      </script>
   </body>
</html>

In the above code, we have created two textboxes, one with kilometers and another with meters. In data property, the kilometers and meters are initialized to 0. There is a watch object made with two functions kilometers and meters. In both the functions, the conversion from kilometers to meters and from meters to kilometers is done.

As we enter values inside any of the textboxes, whichever is changed, Watch deals with updating both the textboxes. We don't need to uniquely allocate any events and wait for it to change and do the additional work of validating. Watch deals with updating the textboxes with the calculation done in the respective functions.

Let’s take a look at the output in the browser:

Let’s enter some values in the kilometers textbox and see it changing in the meter’s textbox and vice-versa.

Let’s now enter in meters’ textbox and see it changing in the kilometers textbox. This is the display seen in the browser:

A to Z Full Forms and Acronyms

Related Article