首页 > 解决方案 > 变异完成后从组件调用 Vuex 动作

问题描述

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

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

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

在我的组件中,我有:

  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.jsasynchronousvuexstore

解决方案


[1] 你的行为应该returnpromise

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

dispatch[2]当第一个已经完成时再调用另一个resolved

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

推荐阅读