首先在store声明actions
//声明actions
const actions = {
//context表示上下文对象 即store
addAction(context){
context.commit('add',10);
//延迟3秒执行一次reduce
setTimeout(() => {context.commit('reduce')},3000);
//如果console比上面的先出来,而不是按顺序执行上面的代码执行完再执行console,即为异步
console.log("我比reduce先执行了");
},
//commit包装对象
reduceAction({ commit }){
commit('reduce');
}
}
//导出
export default new Vuex.Store({
//导出状态常量
state,
//导出mutations
mutations,
//导出getters
getters,
//导出actions
actions
})
然后修改Count.vue组件
//增加mapActions
import { mapState,mapMutations,mapGetters,mapActions } from 'vuex'
//扩展方法
methods:{
...mapMutations(['add','reduce']),
...mapActions(['addAction','reduceAction'])
}
//调用
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>