Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS: watching two properties

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?

like image 651
李明洋 Avatar asked May 19 '17 14:05

李明洋


People also ask

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

How do I use watch property in VUE JS?

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.

What is the difference between watchers and computed property in Vuejs?

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.

How do you watch objects in Vue?

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 .


1 Answers

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
  }
)
like image 196
Bert Avatar answered Sep 22 '22 19:09

Bert