A brief discussion on the monitoring attribute (watch) in Vue

The concept of listening attributes:

In computer science, watch is a debugging technique used to monitor the value of a specific variable while a program is running. When a program executes under debugger control, the debugger displays the current value of the variable and automatically updates the value as the program executes.
In Vue, watch is a technology used to monitor data changes and respond to them. watch can monitor any data attribute and execute the specified function when the attribute changes.

What does the watch do?

watch can monitor data changes and execute the specified callback function when the data changes. It can do the following things:

  1. Monitor data changes : watch can monitor any data changes on the Vue instance, including simple data types, objects, arrays, and calculated properties.

  2. Receive old and new values : When the data changes, the watch callback function will receive two parameters, namely the new value and the old value. This can facilitate us to compare the data changes and further process accordingly.

  3. Execute response functions : The main function of watch is to execute the response functions we specify so that we can respond promptly to data changes, such as recalculating, rendering views, or sending network requests.

  4. Deep monitoring : watch can also deeply monitor changes in nested objects by configuring the deep option, so that it can also capture changes in properties in nested objects.

  5. Immediate execution : watch can also execute the callback function immediately when initializing the component by configuring the immediate option without having to wait for data changes.

  6. Cancel listening : When a watch listener is no longer needed, you can use the unwatch method to cancel the listening.

To sum up, watch can monitor data changes and perform corresponding operations , which allows us to easily process and recalculate data changes. In actual development, watch is often used to detect changes in form inputs, monitor state changes, and handle asynchronous operations gracefully.

Basic syntax of watch:

// 对象式写法
watch: {
    
    
  // 监听的属性名
  属性名: {
    
    
    handler: function (newVal, oldVal) {
    
    
      // 对属性变化作出响应
    }
  }
}

// 函数式写法
watch: {
    
    
  // 监听的属性名,参数为新旧值
  '属性名'(newVal, oldVal) {
    
    
    // 对属性变化作出响应
  }
}

Among them, handler is a function whose first parameter is the new value of the attribute, and the second parameter is the old value of the attribute.
The attribute name is the name of the attribute that needs to be monitored. When a property changes, watch can trigger the specified response function to handle the change, such as recalculating or sending a request.
watch can monitor changes in data types such as objects, arrays, and calculated properties. You can also use the deep option to deeply monitor changes in nested objects. You can also use the immediate option to immediately execute the callback function.

Learn more about listening properties with examples

Example one:

new Vue({
    
      
  data: {
    
      
    message: 'Hello Vue!'  
  },  
  watch: {
    
      
    // 当 `message` 属性发生变化时,执行 `handleMessageChange` 函数  
    message(newVal, oldVal) {
    
      
      console.log('message changed from', oldVal, 'to', newVal);  
    }  
  },  
  methods: {
    
      
    handleMessageChange(newVal, oldVal) {
    
      
      console.log('message changed from', oldVal, 'to', newVal);  
    }  
  }  
});

In the above example, we observed changes in the message attribute through the watch option. When the value of message changes, the callback function will be triggered and output the new value and the old value.
In addition to executing logic directly in the callback function, you can also use named functions as callback functions, or use arrow functions. In addition, you can return a value in the callback function to perform other operations after the data changes.
In addition to observing changes in data, the watch option can also be used to observe calculated properties or methods. In this case, the callback function will be triggered when the result of the calculated property or method changes.

Example two:

<template>
  <div>
    <p>当前计数:{
    
    {
    
     count }}</p>
    <button @click="increment">+1</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      count: 0,
    };
  },
  watch: {
    
    
    count(newValue, oldValue) {
    
     // 监听 count 变化
      console.log(`count 变化,新值为 ${
    
    newValue},旧值为 ${
    
    oldValue}`);
    },
  },
  methods: {
    
    
    increment() {
    
    
      this.count++; // 改变 count 的值
    },
  },
};
</script>

In the above example, we defined a count data attribute and used watch to monitor its changes. In the button click event, we changed the value of count. The watch monitored the data changes and executed the callback function, outputting the old and new value information.

You can also configure the deep and immediate options to listen deeply and execute the callback function immediately when the component is initialized.

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      person: {
    
    
        name: 'Tom',
        age: 18,
      },
    };
  },
  watch: {
    
    
    'person.name'(newValue, oldValue) {
    
     // 深度监听 person.name 的变化
      console.log(`person.name 变化,新值为 ${
    
    newValue},旧值为 ${
    
    oldValue}`);
    },
  },
  created() {
    
    
    this.$watch('person', (newValue, oldValue) => {
    
     // 深度监听 person 对象及其子属性的变化
      console.log('person 变化', newValue, oldValue);
    }, {
    
     deep: true });
    this.$watch('person.name', (newValue, oldValue) => {
    
     // 初始化时立即执行回调函数
      console.log(`person.name 变化,新值为 ${
    
    newValue},旧值为 ${
    
    oldValue}`);
    }, {
    
     immediate: true });
  },
};
</script>

Here, we use watch to deeply monitor changes in person.name, and use the $watch method to deeply monitor changes in the person object when creating the component. At the same time, we set the immediate option to execute the callback function immediately during initialization.

Advantages and disadvantages of listening properties:

advantage:

  1. Responsive : watch can implement responsive monitoring of data, that is, automatically execute callback functions when data changes, making it easy to process changes in a timely manner.
  2. Flexibility : watch can monitor any data attribute and execute a custom callback function, allowing us to perform corresponding operations according to specific needs.
  3. Deep monitoring : watch can deeply monitor changes in nested objects by configuring the deep option. It not only monitors changes in parent objects, but also captures changes in properties of child objects.
  4. Initial execution : watch can execute the callback function immediately when the component is initialized by configuring the immediate option without having to wait for data changes.
  5. Cancel monitoring : When a watch is no longer needed, you can cancel the monitoring through the unwatch method to avoid unnecessary resource consumption.

shortcoming:

  1. Asynchronous problem : The watch callback function is executed asynchronously. In some specific scenarios, the latest data may not be obtained immediately. If you need to get the latest data immediately, you may need to cooperate with $nextTick or use calculated properties to solve the problem.
  2. Frequent triggering : If the monitored data changes frequently, the watch callback function may be triggered frequently, affecting performance. At this time, you can reduce unnecessary callback triggers by configuring immediate options and optimizing logic.
  3. Complexity : When using multiple watches to monitor multiple data, the complexity of the code may increase, making it slightly more difficult to maintain. In this case, consider using computed properties instead of watches.
So how should we deal with these shortcomings?
  1. Handling asynchronous issues : You can use the $nextTick method to ensure that the callback function is executed after updating the view to obtain the latest data.
watch: {
    
    
  count: {
    
    
    handler(newValue, oldValue) {
    
    
      this.$nextTick(() => {
    
    
        console.log(`count 变化,新值为 ${
    
    newValue},旧值为 ${
    
    oldValue}`);
        // 在这里进行相应的操作
      });
    },
    immediate: true,
  },
}
  1. Optimize frequent triggering : If the monitored data changes frequently, you can consider setting immediate options or optimizing logic to reduce unnecessary callback triggers. For example, you can use the debounce or throttle function to limit the execution frequency of the callback function to avoid excessive firing.
  2. Simplify complexity : When using multiple watches to monitor multiple data, consider using calculated properties instead of watches. Computed properties have automatic dependency tracking and caching mechanisms that simplify code and improve performance.
computed: {
    
    
  countInfo() {
    
    
    return `当前计数:${
    
    this.count}`;
  },
},
watch: {
    
    
  countInfo(newValue, oldValue) {
    
    
    console.log(`countInfo 变化,新值为 ${
    
    newValue},旧值为 ${
    
    oldValue}`);
  },
},

In this way, the code will be clearer and easier to maintain by listening for changes in count through the calculated attribute countInfo.

To sum up, watch provides a convenient and powerful data monitoring technology, but you need to pay attention to handling asynchronous issues and frequent triggering situations, and choose the best data monitoring method according to the actual scenario.

Scenarios for using watch:

  1. Data monitoring : When the data changes, you can use watch to monitor the data changes and perform corresponding operations when the data changes. For example, monitor changes in form fields. When the form fields change, you can perform real-time verification, calculation, or send requests based on the new values.

  2. Asynchronous operations : When you need to monitor the results or status of asynchronous operations, you can use watch to monitor changes in asynchronous operations. For example, monitor the results of a network request. When the request returns, you can update the state of the component or perform subsequent operations based on the returned data.

  3. Route changes : When routes change, such as switching pages or parameter changes, you can use watch to monitor changes in the $route object, and perform corresponding page updates or data loading operations based on the new routing information.

  4. Deep monitoring of objects or arrays : When you need to deeply monitor changes in the internal properties of an object or array, you can use watch to perform deep monitoring. For example, listening to a complex data structure, when a certain attribute changes, the corresponding operation can be triggered.

  5. State management : When using state management tools (such as Vuex), you can use watch to monitor state changes and perform corresponding processing based on state changes. For example, listen for changes in a certain state, update the view or trigger other operations when the state changes.

All in all, watch is suitable for scenarios where you need to monitor data changes and perform corresponding operations, especially when you need to handle asynchronous operations, deeply monitor objects or arrays, and respond to routing changes.

There are several points you need to pay attention to when using watch:

  1. It is mainly used to monitor changes in certain specific data to perform certain specific business logic operations. It can be regarded as a combination of computed and methods;
  2. Data sources that can be monitored: data, props, and data in computed;
  3. watch supports asynchronous;
  4. Caching is not supported, and changes in monitored data will directly trigger corresponding operations;
  5. The listening function has two parameters. The first parameter is the latest value, and the second parameter is the value before input. The order must be new value, old value.

If you have anything to add, please leave a message in the comment area!

Guess you like

Origin blog.csdn.net/He_9a9/article/details/132730654