1.问题呈现:计时器案例
得出结论:在mutations函数中不能写异步的代码。
此时我们就引出了Action
Action用于处理异步任务。
如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据。
2.定义Action
const store=new Vuex.Store({
state:{
count:100
},
mutations:{
// 这里的step接收传递过来的参数
add(state){
state.count++
}
},
actions:{
// 定义了一个新的函数addAsync
addAsync(context){
setTimeout(()=>{
context.commit('add')
//这里的commit只能调用mutations中的函数
},1000)
}
}
})
3.触发Action
//触发Action
methods:{
Handler1(){
//在调用dispatch函数
this.$store.dispatch('addAsync')
}
}
效果图:
4.触发actions异步任务时携带参数:
1.定义actions
const store=new Vuex.Store({
state:{
count:100
},
mutations:{
// 这里的step接收传递过来的参数
add(state,step){
state.count+=step
}
},
actions:{
// 定义了一个新的函数addAsync
addAsync(context,step){
setTimeout(()=>{
context.commit('add',step)
//这里的commit只能调用mutations中的函数
},1000)
}
}
})
2.触发actions
methods:{
Handler1(){
//在调用dispatch函数
this.$store.dispatch('addAsync',5)
}
}
效果图:
5.触发actions的第二种方式
//1.从vuex中按需导入mapActions函数
import {mapActions} from 'vuex'
通过刚才导入的mapActions函数,将需要的actions函数,映射为当前组件的methods方法:
methods:{
...mapActions(['addAsync'])
}
效果图: