How to call function from watch?

If you want to use watch to observe your property, you could call your method it with this.foo:

data: function ()  {
    return {
       questions: []
    }
},
    
watch: {
   questions: {
       handler: function(val, oldVal) {
           this.foo(); // call it in the context of your component object
       },
       deep: true
    }
},      
    
methods: {
    foo() {
        console.log("foo called");
    }
}

To answer your question about handler: It is a keyword property that can take either a function expression (as in the example) or a reference to a function, such as:

function myHandler() { ... } // Defined somewhere outside of the vue component object
    
...
    
handler: myHandler,
    
...

Just out of curiosity: Do you need to watch a property in order to do something every time it changes or could computed properties solve your problem as well?


Just to add to the answer from @nils

handler: 'foo'

also works if the function foo is within methods.

Bit shorter than

handler() {
    this.foo()
}

Tags:

Vue.Js