Suppose I have two data properties:
data() {
return {
a: false,
b: false,
}
}
When a
and b
become true
at the same time, I want to carry out a related task.
How can I use a watch method in Vue to achieve this?
Yes, you can setup watcher on computed property, see the fiddle.
The Vue. js Watcher or watch property allows the developers to listen to the component data and run whenever they change a particular property. The watcher or watch property is a unique Vue. js feature that lets you keep an eye on one property of the component state and run a function when that property value changes.
Computed properties are used to calculate the value of a property based on some other conditions. Watchers, on the other hand, are not primarily used for changing the value of a property; instead, they are used to notify you when the value has changed and let you perform certain actions based on these changes.
Deep watcher over array of objects. vue , we have to import it in the App. vue file and pass users as a prop . In User. vue , we are using watcher over the value which is changing and we are also using user.name property instead of user so that vue can detect the change happening to user.name .
Watch a computed value.
computed:{
combined(){
return this.a && this.b
}
}
watch:{
combined(value){
if (value)
//do something
}
}
There is a sort of short hand for the above using $watch.
vm.$watch( function () { return this.a + this.b }, function (newVal, oldVal) { // do something } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With