Vue.js Watchers

As we know computed properties are handy but there are multiple use-cases where you will require a watcher to be present while there is a change in the property value. A watcher is helpful in binding data and detecting changes and reacting to them whenever it’s required. It helps you to react to the changes in the Data. Most of the Async functionalities are being handled by watchers in Vue.js.  You can have a look at the previous tutorial in order to understand how the computed properties work. Let’s get started with seeing a simple example which will enable you to run a live clock on the screen. We will make a color changing watch using the hex code generator. The code goes as below

<div id="app"> {{date}} </div>

Note the $el that refers to the ROOT element. Vue gives a reference to the element on the screen and this leads us to directly manipulate it out.

In the code above we are changing the date every one second and computing time and then the time updates the date property, on the other hand whenever this Async Change takes place we go ahead and update the background color of the app. The code for generating colors is out of the scope of this Article and is covered in the JavaScript How To’s. You can have a look at it. But the entire point of this article is to show how the watcher to a particular property has the same name as the property and it gets updates as there is a change in the Property. This trigger can be used in various places but we are using it in changing the color of the app itself. The sample GIF is shown below. You can alternatively have a look at the JSFiddle code as well.

Vue.js watchers for Async Updates

Vue.js watchers for Async Updates


With this, we can conclude that the watchers are pretty necessary in order to make an application react to various Async Events. The above example sets the base for the way in which we can use watchers in order to react to the Async calls. What do you think can be the other utilities of Watchers. Can you think of some events where watchers come handy?

Also published on Medium.

Join our 2500+ fellow readers

Join our 2500+ fellow readers

Joining our mailing list will for sure keep you at the top of Web Development Ecosystem. Connect with us and also other fellow developers.

You have Successfully Subscribed!

Pin It on Pinterest

Share This