突变完成后从组件调用Vuex操作

问题描述 投票:0回答:1

我有一个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个回答
0
投票

[1]您的操作应为returnpromise

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

[2]当第一个为dispatch时呼叫另一个resolved

created () {
  this.getUserModules().then(response => {
    this.getUserSpecials()
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.