Skip to main content
What Are Vue.js Watchers and How Do They Work

What Are Vue.js Watchers and How Do They Work?

in this tutorial, We’ll explore Vue.js watchers with examples. I will cover here syntax, usage, benefits, and advanced techniques to use it. The watch function is used to trigger a callback whenever a piece of reactive state changes.

What is a Vue.js Watcher

A watcher is a useful feature that allows us to monitor an application state and trigger actions based on these changes. You can also access the old value as well as the new value that it has changed to.

Syntax:

watch: {
 propertyName(newVal, oldVal) {
  // Custom logic to execute when propertyName changes
 }
}

Parameters are:

  • propertyName: The name of the property being watched.
  • newVal: The new value of the property.
  • oldVal: The previous value of the property.

Simple Watchers

watch: {
 counter(newVal, oldVal) {
  console.log('Counter changed from', oldVal, 'to', newVal);
 }
}

Let’s take another example to define a variable and watch properties value:

import { ref, watch } from "vue";
const message = ref("Hello Vue!");

watch(message, (newValue, oldValue) => {
 // do something with newValue and oldValue.
});

in the above code, I have imported ref and watch from the base library, Also defined message variable and call watch method. We are able to access its new value or previous value and perform any preferred action once the message value changes.

I have already covered below vuejs tutorial:

Deep Watcher

The simple vue.js watcher does not support nested object properties, You can achieve this by using an optional deep property in our watcher to true.

watch: {
 'obj.prop': {
  handler(newVal, oldVal) {
   console.log('obj.prop changed from', oldVal, 'to', newVal);
  },
 deep: true
 }
}

The working example:

export default {
  data() {
    return {
      employee: [
        {
          id: 1,
          name: "Adam",
        },
        {
          id: 2,
          name: "Same",
        },
      ],
    };
  },
  watch: {
    someData(newValue, oldValue) {
      console.log("someData changed!");
    },
    deep: true,
  },
};

in the above code, The watcher method will be triggered when a nested property changes.

Immediate Watcher

The watchers are not activated immediately unless the value you are watching has changed. The immediate watcher helps to trigger on initial data and then repeats the process if the data changes.

watch: {
  dataProp: {
    handler(newVal, oldVal) {
      console.log('dataProp changed from', oldVal, 'to', newVal);
    },
    immediate: true
  }
}

Conclusion

The watchers help to perform action based on value changes of properties or variables. You can also see this type of functionality in other UI frameworks like angular 1.6 etc. We have explored all types of watchers simple, deep, and immediate watchers.

Leave a Reply

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