Nuxt-异步操作后等待(this。$ store.dispatch)

时间:2020-09-09 19:34:16

标签: vue.js vuex nuxt.js nuxtjs

我是Nuxt的新手,并且遇到了一个我不理解的问题。

如果我编写如下代码:

const resp1 = await this.$axios.$post('urlCall1', {...dataCall1});
this.$axios.$post('urlCall2', {...dataCall2, resp1.id});

在第二个axios调用中正确设置了resp1.id =>在执行第二个调用之前,我们等待第一个调用完成。

但是,当我在vuex存储区ex中定义异步动作时:

  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 =在action2中未定义

你们能告诉我我错了吗?

谢谢。

最后的注意:这2个动作在不同的商店中

1 个答案:

答案 0 :(得分: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');
    }
}