Vuex action 異步函數


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 = '喵喵'
    }
  },

結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM