Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method is not a function in watcher callback vuejs

I'm coding a project with vueJS. I've a component with following code :

import ProjectsStore from './../stores/ProjectsStore.js';

export default {
    store: ProjectsStore,
    data () {
        return {
            loading: false,
            randomProject: null,
        }
    },
    computed: {
        projects () {
            return this.$store.state.projects;
        },
        commits () {
            return this.$store.state.commits;
        }
    },
    methods : {
        setCommit : ()=> {
            // code here
        }
    },
    watch: {
        projects: (value) => {
            this.setCommit()
        }
    },
    mounted () {
        this.$store.dispatch('loadProjectsList')
    }
}

I've following error in projects watch callback :

this.setCommit is not a function

I put a console.log (this) in callback and it displays an default object not a VueComponent.

Did I make something wrong ?

Thanks for your help.

like image 405
amiceli Avatar asked May 14 '17 15:05

amiceli


1 Answers

Instead of trial and error of changing the syntax and to see what works, its better if you understand why a particular piece of code works.

As mentioned in the vue documentation:

Don’t use arrow functions on an instance property (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.

If you are new to es6 arrow functions here is a pretty good explantion of arrow function's this binding works.

Once you clearly understand then no more trial and error

Hope my answer was of some help to you

like image 91
Vamsi Krishna Avatar answered Oct 27 '22 17:10

Vamsi Krishna