vue.js - 变异完成后从组件调用 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
工作正常,但我想知道是否有更优雅的方法来做到这一点。
解决方案
[1] 你的行为应该
return
是promise
getUserModules ({ commit, dispatch, }) {
return api.get(/user/modules).then((response) => {
commit('setUserModules', response);
})
}
dispatch
[2]当第一个已经完成时再调用另一个resolved
created () {
this.getUserModules().then(response => {
this.getUserSpecials()
})
}
推荐阅读
- r - 自动设置 ggplot 边距以包含 geom_text
- python - 为什么我在 Code jam 2018 “再次拯救世界”中的回答是错误的?
- python - python如何连接两个字典
- ruby-on-rails - Ruby on Rails:如何使用 AWS Cognito 池以用户身份访问 S3?
- javascript - 如何在 VUE 组件的 Scoped 区域中使用 JSON 数据
- java - io.github.dropwizard-jobs 的 Maven 依赖项
- cuda - 函数名称中“i”的含义`cusparse
axpyi` 和 `cusparse 多蒂` - java - 单元测试,Debug 和 Run 模式下的 Mock 对象
- c# - 使用 Dapper 映射一对多(一个对象的两个列表)
- c++ - 索引问题