mutations 中的 methods 必须是同步的,但是使用 actions,可以实现代码的异步执行:
mutations: {
increment(state) {
state.counter += 2;
},
increase(state, payload) {
state.counter = state.counter + payload.value;
},
},
actions: {
increment(context) {
setTimeout(() => {
context.commit('increment');
}, 2000);
},
increase(context, payload) {
context.commit('increase', payload);
},
},
不同于调用mutations中的方法,要使用 actions, commit
必须改成 dispatch
:
methods: {
addOne() {
// this.$store.commit('increment');
this.$store.dispatch('increment')
}
}
以及:
methods: {
addOne() {
this.$store.dispatch('increase', { value: 10 });
},
},