3

I want to watch a prop which is an object so i have

<script>
export default {
    watch:{
        filter: {
            handler:(newval)=> {
               console.log("i have new data",newval) //this works
               this.fetchData(); //throws an error
            },
            deep: true
        }
    },
    props:{
        filter:{
            type:Object,
            required:true
        }
    },
    data: () => ({
        pagination: {},
        items: []
    }),
    methods:{
        fetchData(){
            console.log("am fetching the data");
        }
    }
}

The above watcher works as the console.log displays the new value but i cannot execute a method as on the watch am getting an error Error in callback for watcher "filter": "TypeError: _this.fetchData is not a function". How can i execute a method on a deep watcher.

1 Answer 1

4

Move Arrow function to simple function for handler method. Change handler:(newval)=> { to handler: function (newval) {:

Vue.js docs:

Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()).

handler: function (newval) {
  console.log("i have new data",newval) //this works
  this.fetchData(); // it should work
},

Sign up to request clarification or add additional context in comments.

1 Comment

@GEOFFREYMWANGI stackoverflow.com/questions/34361379/ddg#34361380 Arrow functions have a different scoping than the “function” keyword, so your this is not what you expect with an arrow function. That’s the explanation of why Vue says to not use arrow functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.