Vue's watch and computed use

Both in Vue watchand Vue computedare used to monitor data changes, but their usage scenarios and implementation methods are slightly different.

watchIt is used to monitor a specific data change, and when the monitored data changes, the corresponding callback function will be executed automatically. watchThe usage is as follows:

watch: {
  myData: function(newValue, oldValue) {
    // do something when myData changes
  }
}

In the above code, myDatait is the monitored data. When its value changes, watchthe callback function will be automatically executed and the new value newValueand old value will be passed in oldValue.

computedIt is used to calculate a certain value, which will be automatically updated according to changes in the data it depends on. The difference watchis that computeda new value is returned instead of executing the callback function. computedThe usage is as follows:

computed: {
  myComputedValue: function() {
    // calculate myComputedValue based on other data
    return result;
  }
}

In the above code, myComputedValueit is the calculated new value. Its calculation is based on other data. When the data changes, it computedwill automatically recalculate a new value and return it.

It should be noted that computedthe returned value is automatically updated according to the change of the data it depends on, and the calculation result will be cached and will not be recalculated until the data it depends on changes. Therefore, in some scenarios that require calculation results, it is more convenient and efficient to use computedthan to use .watch

Guess you like

Origin blog.csdn.net/m0_72446057/article/details/129154766