首页 > 解决方案 > 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 个动作在不同的商店中

标签: vue.jsvuexnuxt.jsnuxtjs

解决方案


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');
    }
}

推荐阅读