在vuex里面,mutations是处理同步的,actions是处理异步的
例如:点击按钮使state里面的某个值在2秒之后加1
//mutations函数
export default {
//定义一个加法函数,其中count在state里定义,初始值为0
addN(state,step) {
state.count += step
}
}
//actions函数
export default {
//异步函数
addAsync(context,step) {
setTimeout(() => {
context.commit('addN',step)
},1000)
}
}
//在点击按钮的页面用 this.$store.dispatch() 方法调用actions里面的函数
//点击事件
asyncBtn() {
//第一种调用方法
this.$store.dispatch('addAsync',5)
}
//第二种调用方法
//全局引入mapActions
import { mapActions } from 'vuex'
methods:{
//把需要的函数名写在里面
...mapActions(['addAsync'])
asyncBtn(){
this.addAsync(5)
}
}