How does the watch function monitor changes in responsive data and execute corresponding logic?

watchFunctions are functions used in Vue to monitor responsive data changes and execute corresponding logic or side effects when the data changes. It can monitor changes in responsive data, including object properties, changes in arrays, nested objects and arrays, etc.

watchThere are two ways to use functions: callback-based watch and listener-based watch.

  1. Watch based on callback function:

    import { watch } from 'vue';
    
    const count = ref(0);
    
    watch(count, (newValue, oldValue) => {
      console.log(`count的值从${oldValue}变为${newValue}`);
    });
     

    In the example above, changes watchare monitored by the function count. Whenever countthe value of is changed, the callback function will be triggered, passing in the current value newValueand the last value oldValue. In the callback function, corresponding logic or side effects can be performed.

  2. Listener based watch:

    import { watch } from 'vue';
    
    const obj = reactive({
      name: 'Tom',
      age: 18,
    });
    
    watch(() => obj.age, (newValue, oldValue) => {
      console.log(`age的值从${oldValue}变为${newValue}`);
    });
     

    In the example above, changes watchare monitored by the function obj.age. The listener here is a reactive getter function, and obj.agethe callback function will only be triggered when the value of the value changes.

In addition to the method based on the callback function and the listener, watchthe function also provides some other options to control the monitoring behavior, such as immediate the option to execute the callback function once immediately.

In summary, watchfunctions can be used to monitor changes in reactive data and execute corresponding logic or side effects when the data changes.

Guess you like

Origin blog.csdn.net/weixin_39273589/article/details/132108974