Action類似mutation,不同在於:
(a).Action提交的是mutation,而不是直接變更狀態。
(b).Action 可以包含任意異步操作.
export default{ showHeader:({commit})=>{ commit('showHeader') }, hideHeader:({commit})=>{ commit('hideHeader') }, showLoading:({commit})=>{ commit('showLoading') }, hideLoading:({commit})=>{ commit('hideLoading') } }
分發Action
Action通過store.dispatch方法觸發:
store.dispatch('hideHeader')
Action可以異步操作:
actions:{ incrementAsync({commit}){ setTimeout(() =>{ commit('hideHeader') },1000) } }
//2
hideHeaderAsync:({commit})=>{
setTimeout(()=>{
commit('hideHeader')
},1000)
}
在組件中分發Action
在組件中用this.$store.dispatch('')分發Action,或者使用mapActions輔助函數將組件的methods映射為store.dispatch調用(需要先引入store);
watch:{ //監聽路由 $route(to,from){ // console.log(to.path); if (to.path=='/user-info') { this.$store.dispatch('hideHeader'); }else{ this.$store.dispatch('showHeader'); }; } }
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment' // 映射 this.increment() 為 this.$store.dispatch('increment') ]), ...mapActions({ add: 'increment' // 映射 this.add() 為 this.$store.dispatch('increment') }) } }
組合Action
store.dispatch
可以處理被觸發的action的回調函數返回的Promise,並且store.dispatch仍舊返回Promise:
actions:{ actionA({commit}){ return new Promise((resolve,reject) =>{ setTimeout(()=>{ commit('someMutation') },1000) }) } }
store.dispatch('actionA').then(()=>{
//...
})
//另一個action中也可以
actions:{
//...
actionB({dispatch,commit}){
return dispatch('actionA').then(()=>{
commit('someOtherMutation')
})
}
}
如果利用async/await,可以如下組合action:
actions:{
async actionA({commit}){
commit('gotData',await getData())
},
async actionB({dispatch,commit}){
commit('gotOtherData',await getOtherData())
}
}
一個store.dispatch在不同模塊中可以觸發多個action函數,這種情況下,只有當所有觸發函數完成后,返回的Promise才會執行。