Vuex-Actions学习
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才会执行。