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. 为什么span的color非要内联样式才起作用?2. docker - 如何修改运行中容器的配置3. 请问一下各位老鸟 我一直在学习独孤九贱 现在是在tp5 今天发现 这个系列视频没有实战4. 手机开发 - Android蓝牙模块连接后怎么接收数据?求助5. 在cmd下进入mysql数据库,可以输入中文,但是查看表信息,不显示中文,是怎么回事,怎新手,请老师6. html5 - H5做的手机分享页微信更新后,分享出去不再默认显示第一个图 作为缩略图7. 老师,请问我打开browsersync出现这个问题怎么解决啊?8. css - div设置float:left后高度设置自动会无效 ?9. 求救一下,用新版的phpstudy,数据库过段时间会消失是什么情况?10. docker start -a dockername 老是卡住,什么情况?

网公网安备