by Sai gowtham

How to use Watchers in Vue.js

In this tutorial, we will learn about Watchers in Vue.js with the help of examples.

Watchers

In Vue, watchers help us to watch every change in the data properties.it means if we assign a watcher to a particular data property it keeps track the every data change occurred to this property.

Let’s see an example.

We need to define our watcher inside the watch property object.

<template>
  <div>
    <h1>{{ count }}</h1>
    <button @click="count += 1;">Increment</button>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      count: 0
    };
  },
  watch: {    //the function runs every time when a count data property changes    count: function(value) {      // we can access the count value in function parameter      if (value === 5) {        setTimeout(() => {        // resetting the count value          this.count = 0;        }, 300);      }
    }
  }
};
</script>

Here we added our watcher to the count data property so that our watcher function runs every time when a new data is added to the count property.

Inside our watcher function, we added a condition if the count valuereaches to 5 we are resetting the counter.

Note: The name of the watch function and data property should be same.

You also checkout How to watch an array of objects.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course