Search code examples
vue-componentvuejs2computed-properties

Watching computed properties


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?


Solution

  • 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}`);
            }
        }
    });