javascript - 请问下面的函数写法什么意思?
问题描述
在vuex中的mutations中定义的一个函数,在组件中调用
//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}); }}
我的问题是为什么在调用setCart函数的时候不用传入state参数,目测如果调用的时候不传state参数的话,addCart函数执行的时候就会自动将在store中的state传入进去,这样的原理是什么??这是自己半个月前写的代码,现在看怎么也不理解了。。
问题解答
回答1:去看看源码就知道了。
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})
下面是commit方法的定义
this.commit = function boundCommit (type, payload, options) { // store 就是你想要的答案 return commit.call(store, type, payload, options)}回答2:
this.setCart()被映射为this.$store.commit(’setCart’)
相关文章:
1. windows误人子弟啊2. 冒昧问一下,我这php代码哪里出错了???3. MySQL主键冲突时的更新操作和替换操作在功能上有什么差别(如图)4. python - linux怎么在每天的凌晨2点执行一次这个log.py文件5. 数据库 - Mysql的存储过程真的是个坑!求助下面的存储过程哪里错啦,实在是找不到哪里的问题了。6. 实现bing搜索工具urlAPI提交7. mysql优化 - MySQL如何为配置表建立索引?8. 如何用笔记本上的apache做微信开发的服务器9. 我在网址中输入localhost/abc.php显示的是not found是为什么呢?10. 关于mysql联合查询一对多的显示结果问题
