📅  最后修改于: 2023-12-03 15:35:38.370000             🧑  作者: Mango
In Vue.js, watch
is a powerful feature that allows developers to watch for changes to data properties and perform actions based on those changes. A watch
handler is a function that gets executed every time the data being watched changes.
watch: {
'propertyName': function(newValue, oldValue) {
// Handle the change
}
}
propertyName
: The name of the property being watched.newValue
: The new value of the property.oldValue
: The old value of the property before the change.With watch
, developers can perform actions based on changes to a specific property. For example, if you want to perform a calculation every time the price
property changes, you can write the following watch
handler:
data() {
return {
price: 10.0,
tax: 0.16,
total: 0.0
};
},
watch: {
'price': function(newValue, oldValue) {
this.total = newValue + (newValue * this.tax);
}
}
In this example, we're watching the price
property, and every time it changes, we're updating the total
property based on the new price
and the tax
rate.
watch
handlers to your component.watch
, you need to make sure that you're not creating an infinite loop that causes the function to run indefinitely.immediate
option to run the watch
handler immediately when the component mounts, even if the data hasn't changed yet.watch: {
'propertyName': {
immediate: true,
handler: function(newValue, oldValue) {
// Handle the change
}
}
}