A function defined in mutations in vuex is called in the component
//store.js在mutations中定义
addCart:function (state,{goodIndex,foodIndex}) {
state.goods[goodIndex].foods[foodIndex].count++;
},
//组件中调用
methods:{
...mapMutations(['addCart','removeCart','setCart']),
addCartItem:function(){
this.setCart({goodIndex:this.goodIndex,foodIndex:this.foodIndex});
}
}
My question is why there is no need to pass in the state parameter when calling the setCart function. Visually, if the state parameter is not passed when calling, the addCart function will automatically pass in the state in the store when it is executed, so What is the principle? ? This is the code I wrote half a month ago, but now I don’t understand it. .
伊谢尔伦2017-06-26 10:58:52
Just go and look at the source code and you will know.
export const mapMutations = normalizeNamespace((namespace, mutations) => {
const res = {}
normalizeMap(mutations).forEach(({ key, val }) => {
val = namespace + val
res[key] = function mappedMutation (...args) {
if (namespace && !getModuleByNamespace(this.$store, 'mapMutations', namespace)) {
return
}
// 在这里调用了commit方法
return this.$store.commit.apply(this.$store, [val].concat(args))
}
})
return res
})
The following is the definition of the commit method
this.commit = function boundCommit (type, payload, options) {
// store 就是你想要的答案
return commit.call(store, type, payload, options)
}