Vuex 및 타이프스크립트를 사용하는 올바른 방법은 무엇입니까?
지금까지 그 주제에 대해 내가 찾은 유일한 정보는 이 기사였다.
저는 2개의 모듈로 스토어를 구현하려고 합니다.
export interface RootState {
/** root state props **/
}
const store: StoreOptions<RootState> = {
modules: {
foo,
bar,
},
};
export default new Vuex.Store<RootState>(store);
다음으로 두 개의 모듈이 있습니다.
export interface FooState {
//(...)
}
export const foo: Module<FooState, RootState> = {
//(...)
};
export interface BarState {
//(...)
}
export const bar: Module<BarState, RootState> = {
//(...)
};
foo 모듈의 getter를 사용하여 액세스바 상태를 만들어야 하는 상황이 발생할 때까지 모든 것이 정상이었습니다.
export const getters: GetterTree<FooState, RootState> = {
getInfo: (state, {}, rootState) => number {
const value = rootState.bar.somevalue;
//(...)
},
};
rootState에 바 속성이 없음을 설명하는 보풀 오류가 발생했습니다.고민 끝에 원래의 루트 스테이트인터페이스 변경 오류를 해결할 수 있었습니다.
export interface RootState {
/** root state props **/
foo: FooState;
bar: BarState;
}
문제가 해결되어 IDE 인텔리센스에 매우 적합합니다.
이 아파치 맞습니까?StoreOptions에서 사용하는 RootState 인터페이스에 모든 모듈을 추가하려면?
또, 이러한 타입의 인터페이스(Store Options, Module, Getter Tree 등)에 관한 문서가 부족한 것 같습니다.Vuex는 타이프 스크립트에서 사용할 수 있을 만큼 성숙합니까?
편집: 언급을 잊었습니다.나 이거 캐스팅해야 돼.$store는 컴포넌트에서 스토어를 액세스할 때 사용합니다(vuex-class로 최소화할 수 있습니다).그것에 대해 답변 없이 열린 질문이 있는 것 같다.아직까지는 다른 해결책이 없을 것 같은데, 맞죠?
Vuex는 다음 vuex Import를 사용하여 활자 스크립트와 완벽하게 호환됩니다.
import {GetterTree, MutationTree, ActionTree} from "vuex"
아래 예제는 형식 설명에서 vuex를 사용하는 가장 쉽고 완벽한 방법을 보여 줍니다.
주요 저장소 파일:
import Vue from 'vue'
import Vuex from 'vuex'
import { GetterTree, MutationTree, ActionTree } from "vuex"
import MySubModule from '@/store/submodule'
Vue.use(Vuex)
class State {
userId: string | null = null;
}
const getters = <GetterTree<State, any>>{
};
const mutations = <MutationTree<State>>{
setUserId(state, payload) {
state.userId = payload;
}
};
const actions = <ActionTree<State, any>>{
fetchUserId(store) {
}
};
export default new Vuex.Store({
state: new State(),
mutations: mutations,
actions: actions,
modules: {
subModuleName: MySubModule,
//other submodules
}
})
하위 모듈 저장소 파일:
import { GetterTree, MutationTree, ActionTree } from "vuex"
class State {
}
const mutations = <MutationTree<State>>{
};
const actions = <ActionTree<State, any>>{
};
const MySubModule = {
namespaced: true,
state: new State(),
mutations: mutations,
actions: actions
};
export default MySubModule;
당신을 돕고 싶어요!
vue 3에서 options api를 사용하거나 VueX에서 typscript를 사용하여 기성품을 사용하고 싶은 분들에게는 매우 골칫거리가 될 것입니다.VueX와 매우 유사할 뿐만 아니라 Typescript와 완벽하게 통합되는 Pinia를 사용할 것을 강력히 권장합니다.
언급URL : https://stackoverflow.com/questions/53807294/how-is-the-correct-way-to-work-with-vuex-and-typescript
'source' 카테고리의 다른 글
| Android 부동 동작 버튼 색상 변경 (0) | 2022.07.17 |
|---|---|
| 왜 구조 자체보다는 구조의 첫 번째 요소의 주소를 사용하는가? (0) | 2022.07.17 |
| vue.js 템플릿에 외부 스크립트 포함 (0) | 2022.07.17 |
| Nuxt js 프로젝트의 config stylelint 파일 (0) | 2022.07.17 |
| 'java' 명령어는 Java 프로그램을 컴파일합니까? (0) | 2022.07.17 |