store.dispatch('increment')
我们可以在 action 内部执行异步操作。
actions: {
incrementAsync({commit}){
setTimeout(() => {
commit('increment')
},1000)
}
}
Actions 支持同样的载荷方式和对象方式进行分发
// 以载荷形式分发
store.dispatch('incrementAsync',{
amount:10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount:10
})
在组件中分发 Action
你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用map Actions辅助函数将组件的methods 映射为store.dispatch 调用
import {mapActions } from 'vuex'
export default{
methods:([
'increment' // 映射 this.increment() 为 this.$store.dispatch('increment')
])
mapActions({
add: 'inctement' // 映射 this.add() 为 this.$store.dispatch('increment')
})
}
组合 Actions
Action 通常是异步的,那么如何知道 action 什么时候结束。
你需要明白 store.dispatch 可以处理被处触发的action 的回调函数返回的Promise并且 store.dispatch 仍旧返回Promise
actions: {
actionA({commit}){
return new Promise((resolve)=>{
setTimeout (() => {
commit('someMutation')
resolve()
},1000)
})
}
}
现在你可以
store.dispatch('actionA').then(()=>{
//...
})
在另一个 action 中也可以
actions: {
actionB({dispath,commit}){
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
我们利用async/ await
// 假设 getData() 和 getOther() 返回的是一个 Promis
actions:{
async actionA ({commit}){
commit('gotData',await getData())
},
async actionB({dispatch,commit}){
await dispatch('actionA') // 等待 actionA 完成
commit('goOtherData', await getOtherData())
}
}
内容版权声明:除非注明,否则皆为本站原创文章。
