반응형
Vuex - 여러 디스패치 후 기능 실행
애플리케이션을 만들고 있어 데이터를 로드해야 하는데 사용자가 고장난 데이터를 보지 못하도록 로드 컴포넌트를 삽입합니다.
현재 로드에 set Timeout을 넣었지만 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
}
}
행동하다
return
그Promise
Axios에 의해 작성되었습니다.return axios.all(...
https://vuex.vuejs.org/guide/actions.html#composing-actions 를 참조해 주세요.
디스패치 콜을 정리하고 모든 콜이 완료될 때까지 기다립니다.
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 })
언급URL : https://stackoverflow.com/questions/54759153/vuex-run-function-after-multiple-dispatches
반응형
'programing' 카테고리의 다른 글
반복 콘텐츠 영역에 추가 (0) | 2022.08.09 |
---|---|
Java에서는 정적 메서드의 덮어쓰기를 허용하지 않는 이유는 무엇입니까? (0) | 2022.08.09 |
Vue 재료 테이블에서 md-selection 속성을 동적으로 변경하면 테이블 레이아웃이 파괴됩니다. (0) | 2022.08.09 |
프로그램을 느리게 실행시키다 (0) | 2022.08.09 |
c의 여러 파일에 의해 사용되는 헤더의 구조를 선언하려면 어떻게 해야 합니까? (0) | 2022.08.09 |