Action
Action 用于处理异步任务。
如果通过异步操作变更数据,必须通过Action,而不能使用Mutations,但是在Action 中还是要通过触发Mutation的方式间接变更数据。
//定义Action
const store = new Vuex.Store({
// ...省略其他代码
//只有mutations中定义的函数,才有权力修改state中的数据
mutations : {
add(state){
state.count++;
}
},
actions:{
addAsync(context) {
setTimeout(()=>{
context.commit('add')
},1000)
}
}
})
//触发 Action
methods:{
handle() {
//触发actions的第一种方式
//这里的 dispatch 函数,专门用来触发 action
this.$store.dispatch('addAsync')
}
}
触发actions异步任务时携带的参数:
//定义Action
const store = new Vuex.Store({
// ...省略其他代码
//只有mutations中定义的函数,才有权力修改state中的数据
mutations : {
addN(state,step){
state.count += step;
}
},
actions:{
addNAsync(context,step) {
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
})
//触发 Action
methods:{
handle() {
//这里的 dispatch 函数,专门用来触发 action
//触发actions 时携带参数
this.$store.dispatch('addNAsync',5)
}
}
this.$store.dispatch()是触发actions的第一种方式,触发actions的第二种方式是:
//1.从vuex中按需导入 mapActions 函数
import { mapActions } from 'vuex';
通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法:
//2.将指定的actions函数,映射为当前组件的methods函数
methods :{
...mapActions(['addAsync','addNAsync'])
}