Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

How to Use Watchers in Vue.js Application

Published on February 25, 2020 49 sec read

In this article, we are going to learn about Vue Watchers. Let get started:

Table of Contents

  1. Watchers
  2. Watch Method 1
  3. Watch Method 2

Watchers

A watcher is a special Vue.js feature that watches every change in the data properties. In short, watcher tracks value change of data variables.

Watcher syntax:

<script>
export default {
  watch: {
  }
}
</script>

We can watch any data variable in two ways.

Watch Method 1

We have to define our watcher inside the watch property object. Have a look at the example:

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

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  watch: {
    count: function(value) {
      // add your condition here
      if (value === 3) {
        // the value is 3 & do a task
      }
    }
  }
};
</script>

Watch Method 2

The watch.name optionally accept 2 parameters. The first value is new & the second value is the old value. Take a look at the example:

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

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  watch: {
    count: function(newValue, oldValue) {
      console.log(newValue, oldValue)
    }
  }
};
</script>

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *