Vuex的简单实例(4)
vuex之mutation
1)你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用。看之前文章中的代码:
// 修改密码状态 store.js
mutations: {
changePassword(state, data) {
state.password = data
}
}
// Login.vue
methods: {
loginHandle() {
// 修改password状态
this.$store.commit("changePassword", this.password);
}
}
vuex之mutation提交载荷(传参)
1)可以向store.commit传入额外的参数,即mutation的载荷。在mutations里面添加2个操作count的方法,一个用来增加,一个用来重置
mutations: {
// ...
addCount(state, n) {
state.count += n
},
resetCount(state, data) {
state.count = data;
}
}
2)在Home.vue的mapState中加入count
// template
<p>{{ count }}</p>
<Button @click="add">+</Button>
<Button @click="reset">reset</Button>
// computed
...mapState(['isLogin', 'username', 'password', 'count']),
3)调用mutations里面添加的操作count的方法
methods: {
add () {
this.$store.commit('addCount', 1)
},
reset () {
this.$store.commit('resetCount', 0)
}
}
4)提交载荷传参
// 使用对象形式的载荷也能实现这种效果
// 很多时候,尤其是当数据比较复杂,使用对象形式的载荷会更好。修改addCount与resetCount
addCount(state, payload) {
state.count += payload.n
},
resetCount(state, payload) {
state.count = payload.data;
}
// 调用的时候以对象的形式传参
methods: {
add() {
this.$store.commit({
type: "addCount",
n: 1
});
},
reset() {
this.$store.commit({
type: "resetCount",
data: 0
});
}
}
Vuex之mapMutations
1)与前面mapState、mapGetters性质相似的辅助函数,在Home.vue中把store.js中的addCount、resetCount方法加入
...mapMutations(["addCount", "resetCount"])
// 调用的时候
add() {
this.addCount({ n: 1 });
},
reset() {
this.resetCount({ data: 0 });
}
// 更多形式
// memthod2
// add() {
// this.$store.commit({
// type: "addCount",
// n: 1
// });
// },
// reset() {
// this.$store.commit({
// type: "resetCount",
// data: 0
// });
// },
// method3
// ...mapMutations({
// theAdd: 'addCount',
// theReset: 'resetCount'
// }),
// add () {
// this.theAdd({n: 1})
// },
// reset () {
// this.theReset({data: 0})
// }
效果一致。