Vue 3 listens to multiple data changes through the watch function

Vue 3  watch listens to data changes through functions. In Vue 3, we can use the following method to listen to multiple data sources:

watch({ firstName: 'first', lastName: 'last' }, function (newValues, oldValues) {
    // 新值和旧值的变化都会触发这个回调
    console.log(newValues, oldValues);
​​​​​​​})

It can be seen that in this  watch function, we can pass an object, the property of the object corresponds to the name of the data source we want to listen to, and the value of the property is the property name corresponding to the data source. Additionally, a callback function can be passed to respond when the data source changes.

In addition, if we want to listen to data changes in an array, we can use  deep attributes for deep listening:

watch(() => { return myArray; }, function (newArray, oldArray) {
  // 数组发生变化时触发这个回调
  console.log(newArray, oldArray);
}, {
  deep: true
​​​​​​​})

In this  watch function, we first return the array that needs to be listened to  myArray. In the third parameter, we pass  deep: true, indicating that we need to perform deep listening. In this way, when any element in the array changes, the callback function will be triggered.

It should be noted that  watch functions in Vue 3 are reactive, which means that if we modify the listened data source in the callback function, this modification will trigger the  watch function again. Therefore, you need to pay attention to issues such as circular dependencies when processing data.

Guess you like

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