Vue - 仅在第一个完成后调用异步操作
Vue - call async action only after first one has finished
我需要从我的组件内部调用 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
当您发送一个动作时,默认情况下它没有 then
回调。仅当操作 return 是 Promise
时才会出现这种情况。您的 axios.get
调用应该 return 为 Promise
,但您并未 return 在操作中调用它。你应该简单地 return 它然后 then
回调将在你的 mounted
钩子中触发。
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) })
},
我需要从我的组件内部调用 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
当您发送一个动作时,默认情况下它没有 then
回调。仅当操作 return 是 Promise
时才会出现这种情况。您的 axios.get
调用应该 return 为 Promise
,但您并未 return 在操作中调用它。你应该简单地 return 它然后 then
回调将在你的 mounted
钩子中触发。
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) })
},