I'm currently learning Vuex and reading this part of the official Vue documentation. I was wondering if there's a particular reason why we would access state
with argument instead of just using this
? I tested if things will work with this
which it did.
Vue Example
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
state.count++
}
}
})
My Example
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment () {
this.count++;
}
}
})
The Vuex store instance is not an ordinary object that has its own this
, it could be seen as black box that offers some input/output for that it passes the state as parameter and then inside its logic (pattern) updates the state according to your mutation, for this
available here:
mutations: {
increment () {
this.count++;
}
}
it refers to the global window
object.
According to @Spinx comments this
refers to vuex instance in version 3 and later and i find that what @Matt said is a good note :
IMO this is a great example of why you should use the explicit parameter since you don't know how your function is bound __Matt