69
votes

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
It will be really helpful to answer if you can elaborate what you are trying to do. Here when getting you are getting this.ID while setting this.userId, I am not sure how will this work. - Saurabh
@saurabh I was trying to set a data property either by route params or component "props" since I can't do both I was thinking of just using a computed property and watch it. But what i really wanted to know was can you watch a computed property? - KArneaud

2 Answers

126
votes

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

Following is the code to set watch on computed property:

const demo = new Vue({
    el: '#demo',

    data() {
        return {
            age: ''
        };
    },

    computed: {
        doubleAge() {
            return 2 * this.age;
        }
    },

    watch: {
        doubleAge(newValue) {
            alert(`yes, computed property changed: ${newValue}`);
        }
    }
});
6
votes
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.