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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With