vuejs2 - Vue - 仅在第一个操作完成后调用异步操作

标签 vuejs2 vue-component vue-router vuex

我需要从组件内部调用 2 个操作,但第二个操作只能在第一个操作 100% 完成其工作后才开始。

我正在尝试这个,但它不起作用

mounted() {
    this.$store.dispatch('coinModule/loadApiCoins')
        .then(() => {
            this.$store.dispatch('coinModule/loadUserCoins')
        })
        .catch(error => {
            console.log(error)
        });
},

这 2 个操作是这些

    loadApiCoins({ commit, dispatch, rootGetters }) {
        Vue.axios({
                method: 'get',
                url: 'https://api.coinmarketcap.com/v1/ticker/',
                transformRequest: [(data, headers) => {
                    delete headers.common.Authorization
                    return data
                }]
            })
            .then(response => { commit('SET_API_COINS', response.data) })
            .catch(error => { console.log(error) })
    },

    loadUserCoins({ commit, dispatch, rootGetters }) {
        Vue.axios.get('http://127.0.0.1:8000/api/coins/')
            .then(response => {
                commit('SET_USER_COINS', response.data)
                commit('SET_USER_PORTFOLIO_OVERVIEW')
            })
            .catch(error => { console.log(error) })
    }

这些应该是相反的。 Screen of my network tab

最佳答案

当您分派(dispatch)操作时,默认情况下它没有 then 回调。仅当操作返回 Promise 时才会出现这种情况。您的 axios.get 调用应该返回一个 Promise,但您没有在操作中返回它。您应该简单地返回它,然后 then 回调将在您的 mounted Hook 中触发。

loadApiCoins({ commit, dispatch, rootGetters }) {
  return Vue.axios({
    method: 'get',
    url: 'https://api.coinmarketcap.com/v1/ticker/',
    transformRequest: [(data, headers) => {
      delete headers.common.Authorization
      return data
    }]
  })
  .then(response => { commit('SET_API_COINS', response.data) })
  .catch(error => { console.log(error) })
},

关于vuejs2 - Vue - 仅在第一个操作完成后调用异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46820669/

相关文章:

javascript - 远程应用程序服务器后面的 Vuepress 为带有 iframe 的页面提供 404

webpack - 什么是点菜组件?我应该使用它吗?

javascript - Vuex 中的 Action 完成后从商店调用组件函数

javascript - 是否可以使用 `require.context` 为 Webpack 进行动态导入?

typescript - this.$store 在 Vue 3 中未定义,带有 Vuex 4 商店和路由器

javascript - 从外部文件访问Vue

javascript - 如何将弹出框内的输入标签绑定(bind)到 Vue 模型

javascript - Vue.js 2 - 渲染子行

javascript - vue-cli 从组件构建一个库并导入它

vue.js - 无法读取 null 的属性(读取 'find' )