How to Use Vue.js watchers for Async Updates?

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>

var app = new Vue({
el: '#app',
data: {
date: ''
created: function() {
this_1 = this;
setInterval(function() {
var time = new Date(); = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
}, 1000)
watch: {
date: function(val) {
var div = document.getElementById('app').style.backgroundColor = '#' + intToRGB(hashCode(val + val.split(':')[2]));

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?

Originally published at The Web Juice.

Like what you read? Give Shiv Kumar Ganesh a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.