vue.js - Nuxt - 异步操作后等待 (this.$store.dispatch)
问题描述
我是 Nuxt 的新手,我遇到了一个我不明白的问题。
如果我编写如下代码:
const resp1 = await this.$axios.$post('urlCall1', {...dataCall1});
this.$axios.$post('urlCall2', {...dataCall2, resp1.id});
在第二次 axios 调用中正确设置了 resp1.id => 我们在执行第二次调用之前等待第一次调用完成。
但是,当我在我的 vuex 商店中定义异步操作时:
async action1({ commit, dispatch }, data) {
try {
const respData1 = await this.$axios.$post('urlCall1', { ...data });
commit('MY_MUTATION1', respData1);
return respData1;
} catch (e) {
dispatch('reset');
}
},
async action2({ commit, dispatch }, data, id) {
try {
const respData2 = await this.$axios.$post('urlCall2', { ...data });
commit('MY_MUTATION2', respData2);
} catch (e) {
dispatch('reset');
}
}
然后在我的 vue 组件中,我触发以下操作:
const resp1 = await this.$store.dispatch('store1/action1', data1);
this.$store.dispatch('store2/action2', data2, resp1.id);
resp1.id 在 action2 中未定义。
我还尝试以“旧方式”管理承诺:
this.$store.dispatch('store1/action1', data1).then(resp1 => this.$store.dispatch('store2/action2', data2, resp1.id))
结果还是一样 => id = undefined in action2
你们能告诉我我哪里错了吗?
提前致谢。
最后说明:这 2 个动作在不同的商店中
解决方案
Vuex 不允许多个参数,因此您必须将其作为对象传递,因此它可能如下所示:
this.$store.dispatch('store2/action2', { ...data2, id: resp1.id });
然后在商店里:
async action2({ commit, dispatch }, { id, ...data }) {
try {
const respData2 = await this.$axios.$post('urlCall2', { ...data });
commit('MY_MUTATION2', respData2);
} catch (e) {
dispatch('reset');
}
}
推荐阅读
- r - 对列中的一组相似值进行分组
- php - 无法在php中获取两个日期之间的日期差
- php - 教义:查询数组类型
- javascript - 计算提示答案时遇到问题
- c# - .NET Core (2.1) Web API 控制器接受请求 url 中的所有内容作为参数
- entity-framework - 实体框架对本地数据执行原始 SQL
- android - 如何仅删除 Facebook 登录按钮上的 Facebook 徽标
- linux - Monit无法启动进程:(退出状态0)--无输出
- ansible - 如何通过ansible将指定的子文件夹复制到目的地
- wordpress - 鼠标滚轮与滑块旋转的交互