【问题标题】:Call Vuex action from component after mutation is complete变异完成后从组件调用 Vuex 动作
【发布时间】:2020-07-01 17:31:10
【问题描述】:

我有一个 Vue 组件,它在其 create 钩子中调用 Vuex 操作(一个 api.get 获取一些数据,然后分派一个突变)。突变完成后,我需要在不同的商店中调用一个操作,具体取决于我商店状态中设置的内容......在这种情况下,getUserSpecials

我尝试在我的操作中使用.then(),但该突变尚未完成,即使api.get Promise 已解决,因此我需要检查的商店状态尚不可用。

有谁知道这样做是否有“最佳实践”?我还考虑过在商店状态上使用观察者。

在我的组件中,我有:

  created () {
   this.getUserModules();
    if (this.userModules.promos.find((p) => p.type === 'specials')) {
     this.getUserSpecials();
    }
  },

methods: {
   ...mapActions('userProfile', ['getUserModules',],),
   ...mapActions('userPromos', ['getUserSpecials',],),
},

在我的商店里有:

const actions = {
  getUserModules ({ commit, dispatch, }) {
  api.get(/user/modules).then((response) => {
   commit('setUserModules', response);
  });
 },
};

export const mutations = {
 setUserModules (state, response) {
  Object.assign(state, response);
 },

};

现在,简单的if 签入我的create 钩子工作正常,但我想知道是否有更优雅的方法来做到这一点。

【问题讨论】:

    标签: vue.js asynchronous vuex store


    【解决方案1】:

    让你的行动返回一个承诺:

    更改:

          getUserModules ({ commit, dispatch, }) {
          api.get(/user/modules).then((response) => {
           commit('setUserModules', response);
          });
         },
    

    收件人:

        getUserModules({commit, dispatch}) {
           return new Promise((resolve, reject) => {
                api.get(/user/modules).then((response) => {
                    commit('setUserModules', response);
                    resolve(response)
                }).catch((error) {
                    reject(error)
                });
            });
        },
    
    

    然后你的created() 钩子可以是:

          created () {
           this.getUserModules().then((response) => {
                if(response.data.promos.find((p) => p.type === 'specials'))
                    this.getUserSpecials();
           }).catch((error){
            //error
           });
          },
    

    【讨论】:

      【解决方案2】:

      [1] 你的操作应该是return a promise

      getUserModules ({ commit, dispatch, }) {
        return api.get(/user/modules).then((response) => {
         commit('setUserModules', response);
        })
      }
      

      [2] 当第一个是resolved 时,调用另一个dispatch

      created () {
        this.getUserModules().then(response => {
          this.getUserSpecials()
        })
      }
      

      【讨论】:

      • 哦,有道理。我没有兑现承诺之前的做法
      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2019-02-02
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多