Vuex 상태에서 비동기적으로 초기화된 API를 사용하려면 어떻게 해야 합니까?
Vue + Vuex를 소개하려고 하는데 비동기 초기화 방식을 사용하는 API를 어디서 초기화해야 할지 고민하고 있습니다.
난 분명히 못 해await다음과 같은 비동기 함수 외부에 있습니다.
import { RequestSystemProxy } from "../../assets/scripts/RequestSystemProxy"
const system = new RequestSystemProxy();
const handle = await system.Initialize();
const state = { ... };
const getters = { ... };
const actions = { ... methods that use 'handle' ... };
const mutations = { ... };
export default {
state,
getters,
actions,
mutations
}
그리고 Vue는 내가 이런 약속을 내보내는 것을 좋아하지 않는다.
import { RequestSystemProxy } from "../../assets/scripts/RequestSystemProxy"
export default (async function () {
const system = new RequestSystemProxy();
const handle = await system.Initialize();
const state = { ... };
const getters = { ... };
const actions = { ... methods that use 'handle' ... };
const mutations = { ... };
return {
state,
getters,
actions,
mutations
}
})();
제 의도는handle안에서.actions여러 가지 비동기 요청을 할 수 있지만, 이는 분명히 다음 시간까지 발생할 수 없습니다.handle해결되었습니다.
좀 헷갈리는데, 이걸 어디에 둬야 할지 모르겠어요.초기화할 수 있을 것 같아handleVue 앱을 초기화하기 전에 글로벌하게 전개됩니다만, 그 때문에 초기화는 구조적으로 사용되고 있는 장소와는 상당히 멀리 떨어져 있습니다.이런 일을 할 때 일반적인 방법이 있나요?
어떤 도움이라도 주시면 감사하겠습니다!
액션은 비동기적일 수 있으므로 참조를 저장하기만 하면 됩니다.system.Initialize()그 약속이 해결되기를 기다리면서 각 액션에 대해 약속하고 접두사를 붙입니다.
import { RequestSystemProxy } from '../../assets/scripts/RequestSystemProxy'
const system = new RequestSystemProxy()
const initPromise = system.Initialize()
const state = { ... }
const getters = { ... }
const mutations = { ... }
const actions = {
async exampleAction (context) {
const handle = await initPromise
// now use handle
}
}
export default {
state,
getters,
actions,
mutations
}
또 다른 옵션은 모듈을 사용하는 것입니다.store.js) 약속을 내보내다
import { RequestSystemProxy } from '../../assets/scripts/RequestSystemProxy'
const system = new RequestSystemProxy()
export default system.Initialize().then(handle => {
// now initialize your store...
return {
state,
getters,
// etc
}
})
그 약속들을 소비하고main.js(또는 기타 등)
import storePromise from 'path/to/store.js'
storePromise.then(store => {
new Vue({
store,
// etc
}).$mount('#app')
})
주의: 이 경우 루트 전에 UI를 처리하는 방법을 고려해야 합니다.Vue인스턴스가 초기화되어 마운트됩니다.
작성해야 합니다.actions(그것은 방법뿐입니다) 스토어 내
const actions = {
async actionName({ state }) {
// write your code in here
},
}
또한 당신은 이것을 쓸 수 있다.
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
언급URL : https://stackoverflow.com/questions/60767946/how-to-use-an-api-that-is-initialized-asynchronously-inside-a-vuex-state
'source' 카테고리의 다른 글
| vuefity 변환 v-text-field 레이블 (0) | 2022.10.22 |
|---|---|
| Vue.js 2의 여러 필드를 검색하는 방법 (0) | 2022.10.22 |
| CPU 코어에 따라 스레드를 확장하는 방법 (0) | 2022.10.22 |
| setState를 사용하여 state.item[1] 상태를 갱신하려면 어떻게 해야 합니까? (0) | 2022.10.22 |
| VueJ의 메서드에서 데이터 변수가 업데이트되지 않음s (0) | 2022.10.22 |