programing

Vue3와 Vuex4 및 TypeScript를 사용하여 스토어 모듈을 설정하는 방법

prostudy 2022. 6. 15. 20:56
반응형

Vue3와 Vuex4 및 TypeScript를 사용하여 스토어 모듈을 설정하는 방법

TypeScript를 사용하여 Vue3/Vuex4에 접속하고 싶은데 아쉽게도 문서가 도움이 되지 않았습니다.

https://next.vuex.vuejs.org/guide/typescript-support.html

초심자였던 저는 간단한 문제 추적 스토어 모듈부터 시작했습니다.문제 모듈 내에서 "글로벌 스토어 인스턴스"를 사용하여 index.ts 파일을 생성하여 자체 등록했습니다.

import {
  ActionContext,
  ActionTree,
  GetterTree,
  MutationTree,
  Store,
} from "vuex";

export default (store: Store<{}>): void => {
  store.registerModule("issues", {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
  });
};

export type Issue = {
  title: string;
  isOpen: boolean;
  createdAt: Date;
};

export type State = {
  issues: Issue[];
};

export type Getters = {
  issues(state: State): Issue[];
};

export type ActionAugments = Omit<ActionContext<State, State>, "commit"> & {
  commit<K extends keyof Mutations>(
    key: K,
    payload: Parameters<Mutations[K]>[1]
  ): ReturnType<Mutations[K]>;
};

export enum ActionType {
  SubmitIssue = "SubmitIssue",
}

export type Actions = {
  [ActionType.SubmitIssue](
    context: ActionAugments,
    submitIssuePayload: SubmitIssuePayload
  ): void;
};

export type SubmitIssuePayload = {
  issueTitle: string;
};

export enum MutationType {
  SubmitIssue = "SUBMIT_ISSUE",
}

export type Mutations = {
  [MutationType.SubmitIssue](state: State, payload: SubmitIssuePayload): void;
};

const state: State = {
  issues: [],
};

const getters: GetterTree<State, State> & Getters = {
  issues: function (state: State): Issue[] {
    return state.issues;
  },
};

const actions: ActionTree<State, State> & Actions = {
  [ActionType.SubmitIssue]: function (
    { commit }: ActionAugments,
    { issueTitle }: SubmitIssuePayload
  ): void {
    commit(MutationType.SubmitIssue, { issueTitle });
  },
};

const mutations: MutationTree<State> & Mutations = {
  [MutationType.SubmitIssue]: function (
    state: State,
    { issueTitle }: SubmitIssuePayload
  ): void {
    const issue: Issue = {
      title: issueTitle,
      isOpen: true,
      createdAt: new Date(),
    };

    state.issues.push(issue);
  },
};

현재 다음과 같은 이유로 인해 셋업에 어려움을 겪고 있습니다.

  • 카피페이스트 했습니다ActionAugments구글에서.커밋 기능에 액세스하려면 Action Context를 직접 재작성해야 합니까?
  • 설정이 아직 올바르지 않습니다.함수store.registerModule이 에러를 나타냅니다.

.

No overload matches this call.
  Overload 1 of 2, '(path: string, module: Module<State, {}>, options?: ModuleOptions | undefined): void', gave the following error.
    Type 'GetterTree<State, State> & Getters' is not assignable to type 'GetterTree<State, {}> | undefined'.
      Type 'GetterTree<State, State> & Getters' is not assignable to type 'GetterTree<State, {}>'.
        'string' index signatures are incompatible.
          Type 'Getter<State, State>' is not assignable to type 'Getter<State, {}>'.
            Property 'issues' is missing in type '{}' but required in type 'State'.
  Overload 2 of 2, '(path: string[], module: Module<State, {}>, options?: ModuleOptions | undefined): void', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'string[]'.ts(2769)
store.ts(26, 3): 'issues' is declared here.
index.d.ts(132, 3): The expected type comes from property 'getters' which is declared here on type 'Module<State, {}>'

글로벌 스토어 인스턴스가 유형이기 때문에 이는 타당합니다.Store<{}>그리고 내 모듈에서는Store<State>

이걸 어떻게 고칠까요?

도와줘서 고마워요!

문제는 모듈스테이트 타입이 루트스테이트가 예상되는 장소에 지정되어 있는데, 이들 타입은 동일하지 않다는 것입니다.

루트 상태 유형을 다음과 같이 하드 코딩하지 않고 개별 유형으로 유지하고 가져오는 것이 좋습니다.{}시간이 지남에 따라 변할 수 있기 때문입니다.

그럴 것 같네요.store: Store<RootState>,GetterTree<State, RootState>root state generic 파라미터가 다음 유형에 영향을 미치는 경우rootStateVuex 컨텍스트에서 사용합니다.

언급URL : https://stackoverflow.com/questions/69557246/how-to-setup-a-store-module-using-vue3-with-vuex4-and-typescript

반응형