Watching computed properties

2019-03-12 06:27发布

问题:

I have a component with the following hash

{ 
  computed: { 
    isUserID: { 
      get: function(){
         return this.userId? 
      } 
  }
}

Should I be watching isUserID or userId for changes? Can you watch computed properties?

回答1:

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

Following is the code to set watch on computed property:

var demo = new Vue({
    el: '#demo',
    data: function(){
        return {
        age: ''
      };
    },
    computed: {
      doubleAge: function () {
            return 2*this.age
        }
    },
    watch: {
      doubleAge: function (val) {
         alert("yes, computed property changed")
       }
    }   
})


回答2:

computed: {
  name: {
    get: function(){
      return this.name;
    }
  }
},
watch: {
  name: function(){
    console.log('changed');
  }
}

This way we can watch over the computed property if it is changed we get notified on the console.