action與Mutation類似,Mutation用於同步函數,action用於異步函數。
異步函數需要通過先action再傳遞到mutations,這樣才能被Devtools記錄下來。
使用方法
1 組件發布行為 dispatch
src\App.vue
methods:{ addition(){ this.$store.commit(INCREMENT) }, updateInfo(){ // this.$store.commit('updateInfo') this.$store.dispatch('aUpdateInfo') } }
2 傳入actions
src\store\index.js
actions:{ //context 上下文 aUpdateInfo(context){ setTimeout(()=>{ context.commit('updateInfo') },1000) } },
3 傳入mutations
src\store\index.js
mutations:{ updateInfo(state){ state.info.name = '喵喵' } }
結果
這樣的異步操作就可以在Devtools里捕獲到了
帶參數和回調
1 組件發布行為 dispatch
src\App.vue
updateInfo(){ // this.$store.commit('updateInfo') this.$store.dispatch('aUpdateInfo','我是攜帶的信息') .then(res=>{ console.log(res); }) }
2 傳入actions
src\store\index.js
actions:{ //context 上下文 aUpdateInfo(context,payload){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ context.commit('updateInfo') console.log(payload); resolve('我完成了') },1000) }) } },
3 傳入mutations
src\store\index.js
mutations:{ updateInfo(state){ state.info.name = '喵喵' } },
結果