携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第22天,点击查看活动详情
一。actions和mutations
<p>
<input type="text" v-model="x" />
<button @click="updatex">修改姓</button>
</p>
<p>
<input type="text" v-model="m" />
<button @click="updatem">修改名</button>
</p>
data() {
return {
// 修改姓
x: "",
// 修改名
m: "",
};
},
methods: {
// 修改性
updatex() {
this.$store.dispatch("updatex", this.x);
},
// 修改名
updatem() {
this.$store.dispatch("updatem", this.m);
},
},
// 异步方法
// 调用actions需要通过dispatch
// 一般进行增加条件判断和发送数据请求
actions: {
updatex(store, value) {
// 通过commit调用mutations
store.commit("UPDATEX", value);
},
updatem(store, value) {
store.commit("UPDATEM", value);
},
},
// 同步方法
// 调用 mutatios需要通过commit
// 一般用于最后一步的结果
mutations: {
UPDATEX(state, val) {
state.firstn = val;
},
UPDATEM(state, val) {
state.lastn = val;
},
},
修改前
修改后
actions和mutations操作数据可以实现多个组件共享数据,操作数据可以直接通过mutations操作数据,但是不建议这么做,还是要通过actions再调用mutations是规范的写法。
一般在actions里面通过commit调用mutations的时候,(commit的第一个参数名会全部大写,这样使别人在阅读代码的时候会很容易就看到了mutations是通过actions里面的commit调用的,更语义化,也利于后期更好的维护代码。)
<ul>
<li v-for="(item, index) in $store.state.list" :key="index">
{{ item }}
<button @click="del(item.no)">删除</button>
</li>
</ul>
methods: {
del(no) {
调用actions
this.$store.dispatch("del", no);
},
},
actions:{
// 删除
del(store, no) {
if (confirm("你确定删除吗")) {
// 找到List数组里no和传过来的no相同的,返回索引,(findIndex)是ES6的方法,返回满足条件的索引
let index = store.state.list.findIndex((r) => r.no == no);
调用mutations
store.commit("DEL", index);
}
},
}
mutations:{
// 删除
DEL(state, index) {
// 根据索引删除数据
state.list.splice(index, 1);
},
}