分享一个vuex的小知识:
使用vuex,修改状态用commit,或者dispatch,如
this.$store.commit('user/age', 10)
this.$store.dispatch('user/age', 10)
也可以使用mapActions和mapMutations进行映射,
使用方法:
...mapActions({
stateChange: 'user/updateUserinfo', // 对应store中模块对应的actions方法名,
}),
将 this.stateChange()
映射为 this.$store.commit('user/updateUserinfo')
...mapMutations({
stateChange: 'user/SET_USERINFO', // 对应store中mutations中的type名
}),
将 this.stateChange()
映射为 this.$store.commit('user/updateUserinfo')
注意:
1:如果有参数传递,直接在绑定的元素上
stateChange(10)
,
或者如stateChange({name: '张三', age: 18})
将需要更新的数据组装好再提交,
假如你在stateChange方法中先将参数进行处理,在组装是不能实现state更新的,
mapActions和mapMutations无法进行异步更新;
2:vuex的模块中namespaced为true时,mapMutations和mapActions都需要加上完整的模块名