Vue3 watch property


Vue3 选项式 APIVue3 Options API

In Vue3,watchThe property is used to listen for changes to a piece of data in the Vue instance and execute the corresponding callback function when the data changes.

watchIt allows us to observe and respond to changes in specific data in the Vue instance, thereby performing some side effects, such as updating the DOM, making network requests, etc.


2. Basic usage of the watch property

In Vue3,watchthe property can be used in the following ways:

Example

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue}to ${newValue}`);
    });

    return {
      count
    };
  }
};

3. Code explanation

In the above code:

  • First, we userefto create a reactive datacount, and set its initial value to 0.
  • Then, we usewatchfunction to listen tocountchanges.watchaccepts two parameters:
    • The first parameter is the data we want to listen to (here it iscount)。
    • The second parameter is a callback function, which will be triggered when the watched data changes. The callback function receives two parameters:
      • newValue: the new value after the data changes.
      • oldValue: the old value before the data changes.

4. Advanced usage of the watch property

In addition to listening to a single data,watchyou can also listen to multiple data, or listen to a complex expression.

4.1 Listening to multiple data

Example

import { ref, watch } from 'vue';

export default {
  setup() {
    const firstName = ref('John');
    const lastName = ref('Doe');

    watch([firstName, lastName], ([newFirstName, newLastName], [oldFirstName, oldLastName]) => {
      console.log(`firstName changed from ${oldFirstName}to ${newFirstName}`);
      console.log(`lastName changed from ${oldLastName}to ${newLastName}`);
    });

    return {
      firstName,
      lastName
    };
  }
};

In this example, we listened tofirstNameandlastNamechanges in two data. When either of them changes, the callback function will be triggered.

4.2 Listening to complex expressions

Example

import { ref, watch } from 'vue';

export default {
  setup() {
    const user = ref({
      name: 'Alice',
      age: 25
    });

    watch(
      () => user.value.age, // Listen to changes in user.age
      (newAge, oldAge) => {
        console.log(`age changed from ${oldAge}to ${newAge}`);
      }
    );

    return {
      user
    };
  }
};

In this example, we use a function to listen touser.agechanges. This approach is suitable for listening to a property within an object.

5. Options for the watch property

watchThe function also accepts a third parameter, which is an optional configuration object that can be used to customize the listening behavior.

Example

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue}to ${newValue}`);
    }, {
      immediate: true, // Execute the callback function immediately
      deep: true // Deep listening, suitable for listening to objects or arrays
    });

    return {
      count
    };
  }
};
  • immediate: true: indicates that the callback function is executed immediately when listening starts, rather than waiting until the data changes.
  • deep: true: indicates deep listening, suitable for listening to changes in objects or arrays.

Vue3 选项式 APIVue3 Options API

Other extensions