Actions用于处理异步任务。
如果通过异步操作变更数据,必须通过 Action,而不能使用Mutation,但是在 Action中还是要通过触发Mutation的方式间接变更数据。
注意: 在Actions 中不能直接修改 state中的数据,要通过 mutations修改。
方法1:this.$store.dispatch
const store = new Vuex.store({
state: {
count: 0
},
mutations: {
add(state) {
state.count++
}
},
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000);
}
},
})
methods:{
handle(){
this.$store.dispatch('addAsync')
}
}
方法2:导入 mapActions
函数
import {mapActions} from 'vuex'
actions: {
subAsync(context){
setTimeout(() => {
context.commit('sub')
}, 1000);
}
}
methods:{
...mapActions(['subAsync']),
decrementAsync(){
this.subAsync()
}
}