Vuex - 多次分派后运行功能 [英] Vuex - Run function after multiple dispatches
问题描述
我正在创建一个应用程序,在某个时刻我需要加载一些数据,但为了让用户看不到损坏的数据,我插入了一个加载组件.
I'm creating an application and at a certain point I need to load some data, but for the user not to see broken data I'm inserting a loading component.
目前我在加载中设置了 setTimeout,但在某些时候 API 响应可能需要 1 秒以上.所以我想只有在所有调度都完成时才更新加载状态.
Currently I put a setTimeout in the load, but at some point the API response can take more than 1 second. So I would like to update the loading state only when all the dispatches become completed.
MainComponent.vue
beforeCreate() {
this.$store.dispatch('responsibles/fetchData')
this.$store.dispatch('events/fetchData')
this.$store.dispatch('wallets/fetchData')
// Need to run this setTimeout after all the above dispatches become completed...
setTimeout(() => {
this.loading = false
}, 1000)
}
store/modules/responsibles.js
const state = {
responsibles: []
}
const actions = {
fetchData({dispatch}) {
function getresponsibles() {
return http.get('responsibles')
}
axios.all([
getresponsibles()
]).then(axios.spread(function (responsibles) {
dispatch('setResponsibles', responsibles.data.data)
})).catch(error => console.error(error))
},
setResponsibles({commit}, responsibles) {
commit('SET_RESPONSIBLES', responsibles)
}
}
const mutations = {
SET_RESPONSIBLES(state, responsibles) {
state.responsibles = responsibles
}
}
store/modules/events.js
const state = {
events: []
}
const actions = {
fetchData({dispatch}) {
function getEvents() {
return http.get('events')
}
axios.all([
getEvents()
]).then(axios.spread(function (events) {
dispatch('setEvents', events.data.data)
})).catch(error => console.error(error))
},
setEvents({commit}, events) {
commit('SET_EVENTS', events)
}
}
const mutations = {
SET_EVENTS(state, events) {
state.events = events
}
}
store/modules/wallets.js
const state = {
wallets: []
}
const actions = {
fetchData({dispatch}) {
function getWallets() {
return http.get('wallets')
}
axios.all([
getWallets()
]).then(axios.spread(function (wallets) {
dispatch('setWallets', wallets.data.data)
})).catch(error => console.error(error))
},
setWallets({commit}, wallets) {
commit('SET_WALLETS', wallets)
}
}
const mutations = {
SET_WALLETS(state, wallets) {
state.wallets = wallets
}
}
推荐答案
让你的动作
返回
由Axios创建的Promise
,例如
Have your actions
return
thePromise
created by Axios, eg
return axios.all(...
参见 https://vuex.vuejs.org/guide/actions.html#composing-actions
将您的调度调用封装在 Promise.all
并等待它们全部完成
Wrap your dispatch calls in Promise.all
and wait for them all to complete
Promise.all([
this.$store.dispatch('responsibles/fetchData'),
this.$store.dispatch('events/fetchData'),
this.$store.dispatch('wallets/fetchData')
]).finally(() => {
// using "finally" so even if there are errors, it stops "loading"
this.loading = false
})
这篇关于Vuex - 多次分派后运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!