简体   繁体   English

如何从动作分派另一个动作并在Vuex中分派另一个动作

[英]How to dispatch another action from an action and dispatch another action in Vuex

In Vuex action, we have the following implementation. 在Vuex动作中,我们具有以下实现。

async actionA({ commit, dispatch }) {
  const data = this.$axios.$get(`/apiUrl`)
  await Promise.all([
    dispatch('actionB', { data: data }),
    dispatch('actionOthers'),
  ]).then(() => {
    commit('mutationA', data)
  })
}

async actionB({ commit, dispatch }, { data }) {
  await this.$axios.$get('/apiUrl', { params: data }).then(res => {
    if (res.length === 0) {
      dispatch('actionC', { data: data })
    }
    commit('mutationB', res)
  })
}

async actionC({ commit, dispatch }, { data }) {
  await this.$axios.$get('/anotherUrl', { params: data }).then(res => {
    commit('mutationC', res)
  })
}

Dispatch actionB from actionA and dispatch actionC from actionB depending on the result of actionB . 调度actionBactionA和派遣actionCactionB根据结果actionB
However, actionA will be resolved before actionC completes. 但是, actionA将在actionC完成之前解决。

How should I cope with such cases? 我应该如何应对这种情况?

If you want to avoid that actionA resolves before actionC completes, you need to await on the dispatch actionC action. 如果要避免actionA在actionC完成之前解决,则需要等待分派actionC操作。

You need to rewrite your actionB like this: 您需要像这样重写actionB:

async actionB({ commit, dispatch }, { data }) {
    const res = await this.$axios.$get('/apiUrl', { params: data })
    if (res.length === 0) {
        await dispatch('actionC', { data: data })
    }
    commit('mutationB', res)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM