Introduction to Vue.js Watchers
Tags: webdev, programming, javascript, vue
Published: 2021-01-25 23:34:12

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at how to define and use Vue.js watchers.

When Should We Use Watchers?
============================

We can use watchers when we want to watch for data changes in reactive properties and do some asynchronous or expensive options as the value changes.

For example, we can use it to watch for changes for an input and then get a joke from the [Chuck Norris API](http://www.icndb.com/api/) when we type in something.

First, we put the following in `src/index.js` :

```
new Vue({  
  el: "#app",  
  data: {  
    message: "",  
    joke: ""  
  },  
  created() {  
    this.debounceGetAllCapsMessage = _.debounce(this.getAllCapsMessage, 500);  
  },  
  methods: {  
    async getAllCapsMessage() {  
      const res = await fetch("https://api.icndb.com/jokes/random");  
      const result = await res.json();  
      this.joke = result.value.joke;  
    }  
  },  
  watch: {  
    message(newMessage, oldMessage) {  
      this.debounceGetAllCapsMessage();  
    }  
  }  
});
```

The code above watches for the change in the `message` property and then call the `debounceGetAllCapsMessage` method, which gets a jokes after a half a second delay.

The `watch` method both takes the new value as the first parameter and the old value as the second parameter.

Then we put the following in `index.html` :

```
<!DOCTYPE html>  
<html>  
  <head>  
    <title>Hello</title>  
    <meta charset="UTF-8" />  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>  
  </head> <body>  
    <div id="app">  
      <input type="text" v-model="message" />  
      <p>{{joke}}</p>  
    </div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>
```

As we can see, we can run an asynchronous operation, add a delay before we perform the operation, and then get the final result.

We can also use `vm.$watch` to watch for a value. It takes up to 3 arguments.

The first is a path to a property, which is a string. It can also be a function with one or multiple things combined to watch.

The second argument is a function that runs when the value changes.

The third argument for `vm.$watch` is an object with some properties. They include:

*   `immediate` — watches for the setting of the initial value

The method returns a function to stop watching for values. This is an optional argument.

We can use it as follows. In `src/index.js` , we have:

```
const vm = new Vue({  
  el: "#app",  
  data: {  
    message: "",  
    joke: ""  
  }  
});

vm.$watch(  
  "message",  
  _.debounce(async function() {  
    const res = await fetch("https://api.icndb.com/jokes/random");  
    const result = await res.json();  
    this.joke = result.value.joke;  
  }, 500)  
);
```

Then `index.html` , we have:

```
<!DOCTYPE html>  
<html>  
  <head>  
    <title>Hello</title>  
    <meta charset="UTF-8" />  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>  
  </head> <body>  
    <div id="app">  
      <input type="text" v-model="message" />  
      <p>{{joke}}</p>  
    </div>  
    <script src="./src/index.js"></script>  
  </body>  
</html>
```

which is the same as what we had before.

In both examples, we should get a new joke after half a second delay displayed.

Conclusion
==========

We can use the `watch` method in the options and object and `vm.$watch` to watch for value changes.

The `vm.$watch` method watches a property given the path to it or a function that returns it or a combination of multiple properties.

`vm.$watch` takes a value changes handler and we can run code in it to handle when the value of a reactive property change.

The `watch` method runs code as the value changes.

Also, the `watch` method both takes the new value as the first parameter and the old value as the second parameter.