What is Vue.js Watch Property?

In Vue.js, the watch property allows you to perform custom logic in response to changes in data properties, computed properties, or other reactive values. It provides a way to observe changes and react to them in a declarative manner.

The watch property can be used in two different ways.

Object-Based Watchers

You can define watchers as key-value pairs in the watch object within a Vue component. The keys represent the property you want to watch, and the values are handler functions that will be called when the watched property changes.

Immediate Watchers

You can also use the immediate option to trigger the handler immediately upon component creation, before the initial render.

Here's how you can use the watch property in a Vue component.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  watch: {
    // Watch for changes in the 'count' data property
    count(newValue, oldValue) {
      console.log(`Count changed from ${oldValue} to ${newValue}`);
    }
  },
  methods: {
    increment() {
      this.count++;
    }
  }
};
</script>

In this example, we're watching the count data property. Whenever count changes, the watcher function defined in the watch object will be called with the new and old values of count.

You can also watch computed properties and other reactive values.

export default {
  data() {
    return {
      firstName: 'John',
      lastName: 'Doe'
    };
  },
  computed: {
    fullName() {
      return `${this.firstName} ${this.lastName}`;
    }
  },
  watch: {
    // Watch for changes in the computed property 'fullName'
    fullName(newValue, oldValue) {
      console.log(`Full name changed from ${oldValue} to ${newValue}`);
    }
  }
};

In this example, we're watching the fullName computed property. Whenever fullName changes, the watcher function will be called with the new and old values of fullName.

The watch property is useful for performing side effects, such as making API calls, updating other data properties, or triggering animations, in response to changes in reactive values within a Vue component.