【发布时间】: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