Both in Vue watch
and Vue computed
are used to monitor data changes, but their usage scenarios and implementation methods are slightly different.
watch
It is used to monitor a specific data change, and when the monitored data changes, the corresponding callback function will be executed automatically. watch
The usage is as follows:
watch: {
myData: function(newValue, oldValue) {
// do something when myData changes
}
}
In the above code, myData
it is the monitored data. When its value changes, watch
the callback function will be automatically executed and the new value newValue
and old value will be passed in oldValue
.
computed
It is used to calculate a certain value, which will be automatically updated according to changes in the data it depends on. The difference watch
is that computed
a new value is returned instead of executing the callback function. computed
The usage is as follows:
computed: {
myComputedValue: function() {
// calculate myComputedValue based on other data
return result;
}
}
In the above code, myComputedValue
it is the calculated new value. Its calculation is based on other data. When the data changes, it computed
will automatically recalculate a new value and return it.
It should be noted that computed
the 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 computed
than to use .watch