gpt4 book ai didi

javascript - Vuex - 多次分派(dispatch)后运行函数

转载 作者:搜寻专家 更新时间:2023-10-30 22:15:15 24 4
gpt4 key购买 nike

我正在创建一个应用程序,在某个时候我需要加载一些数据,但为了让用户看不到损坏的数据,我插入了一个加载组件。

目前我在加载中设置了一个 setTimeout,但在某些时候 API 响应可能需要超过 1 秒。所以我只想在所有调度完成时更新加载状态。

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
}
}

最佳答案

  1. 让您的操作返回 Axios 创建的Promise,例如

    return axios.all(...

    参见 https://vuex.vuejs.org/guide/actions.html#composing-actions

  2. 将您的调度电话包装在 Promise.all 中并等待它们全部完成

    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
    })

关于javascript - Vuex - 多次分派(dispatch)后运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com