Watching computed properties

2019-03-12 06:29发布

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?

2条回答
一纸荒年 Trace。
2楼-- · 2019-03-12 06:39
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.

查看更多
相关推荐>>
3楼-- · 2019-03-12 06:54

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")
       }
    }   
})
查看更多
登录 后发表回答