之前在全局通信的时候讲过使用mapMutations,现在单独拎出来讲一讲
js文件
const store = new Vuex.Store({
state: {
title: "old title",
num: 18,
},
mutations: {
//创建两个方法,更改文字和数字累加
changeText(state) {//不传入参数
state.title = "newTitle"
},
addNum(state, num) {//传入参数
state.num += num
},
}
})index文件
首先导入mapMutations
import {mapMutations} from 'vuex'添加两个按钮,触发事件
<view>
<button @click="changeText">我要更改文字</button>
<button @click="addNum(44)">添加累加</button>
<p>{{title}}</p>
<p>{{num}}</p>
</view>在computed方法获取文字和数字
computed:{
//获取姓名和年龄
num() {
return this.$store.state.num;
},
title(){
return this.$store.state.title;
}
},然后使用辅助函数将methods映射
...mapMutations(['changeText','addNum'])此时点击按钮就会触发相应的事件。
其实,...mapMutations(['changeText','addNum'])这句话就是将组件中的 methods 映射为 store.commit 调用提交函数。
那么使用Mutations提交函数来试一试
js文件不变,
在methods 方法中声明
//Mutations,方法提交,commit
changeText() {
this.$store.commit("changeText");
},
addNum() {
this.$store.commit("addNum",20);
},
// ...mapMutations(['changeText','addNum'])两种方法都是可以实现更改文字和数字累加。个人觉得,类似事件订阅,触发提交或映射到对应的函数就可。
如图

版权声明:本文为weixin_42180036原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。