programing

라우터 내부의 Vuex 스토어 모듈 상태에 액세스합니다.

firstcheck 2022. 7. 3. 19:37
반응형

라우터 내부의 Vuex 스토어 모듈 상태에 액세스합니다.

이 튜토리얼에 따라 TypeScript를 사용하여 모듈로 Vuex 스토어를 셋업했습니다.

지금까지의 내용:

vuex/types.ts:

export interface RootState {
    version: string;
}

vuex/user-profile.ts:

import { ActionTree, Module, MutationTree } from 'vuex';
import { RootState } from './types';

interface User {
    firstName: string;
    uid: string;
}

interface ProfileState {
    user?: User;
    authed: boolean;
}

const state: ProfileState = {
    user: undefined,
    authed: false,
};

const namespaced: boolean = true;

export const UserProfile: Module<ProfileState, RootState> = {
    namespaced,
    state,
};

store.ts:

import Vue from 'vue';
import Vuex, { StoreOptions } from 'vuex';
import { UserProfile } from '@/vuex/user-profile';
import { RootState } from '@/vuex/types';

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
  state: {
      version: '1.0.0',
  },
  modules: {
      UserProfile,
  },
};

export default new Vuex.Store<RootState>(store);

router.ts로 액세스 하고 싶다.authed다음과 같은 스토어 상태를 나타냅니다.

import store from './store';
//...other imports...

const router = new Router({
//... route definitions...
});

router.beforeEach((to, from, next) => {
  const isAuthed = store.state.UserProfile.authed;
  if (to.name !== 'login' && !isAuthed) {
    next({ name: 'login' });
  } else {
    next();
  }
});

코드는 동작하지만(앱은 올바르게 리다이렉트), 컴파일러는 다음과 같은 오류를 발생시킵니다.Property 'UserProfile' does not exist on type 'RootState'정의되어 있지 않기 때문에 이치에 맞지만 모듈 아래에도 표시되어 있지 않은가, 아니면 모듈을 올바르게 정의하지 않은가.

1

     const isAuthed = store.state["UserProfile"].authed; // false

2

    const state:any|State = store.state
    const isAuthed = state.UserProfile.authed; // false

3

    const isAuthed = (<any|State>store.state).UserProfile.authed; // false

이것은 의존관계가 있는 유효한 솔루션이다."vuex": "^4.0.2","vue-router": "^4.0.10"그리고."vue": "^3.1.4".

를 Import 합니다.store에의router모듈 내 상태에 액세스하기 위한 파일:

import store from "@/store/store";

이 경우 모듈명은authModule액세스 할 수 있습니다.statetoken여기서 jwt는 저장됩니다.

let loggedIn = store.state.authModule.token;

더블 캐스트를 추천합니다.1 대 1로, 그리고 1 대 1로 당신이 정말로 원하는 것을 돌려받을 수 있습니다.다음 마지막 router.ts 파일에서 "store"는 Store의 인스턴스이고 나머지 2개의 Import는 단순한 유형입니다.

간결함을 위해 이름, 상태, 게터, 행동, 돌연변이 코드를 생략했습니다.단순한 객체 구조입니다.

store/myModule/types.ts:

export default interface State {
    testValue
}

store/myModule/index.ts:

import RootState from '../types'

const module: Module<State, RootState> = {
    namespaced,
    state,
    getters,
    actions,
    mutations,
}

export default module

store/types.ts:

interface RootState {
  myOtherTestValue: string
}

export default RootState
export { RootState }

store/index.ts:

import RootState from './types'
import myModule from './myModule'

export const cmStore: StoreOptions<RootState> = {
    actions,
    mutations,
    state,
    modules: {
        myModule,
    },
    plugins,

}

export default new Vuex.Store<RootState>(cmStore)

in router.ts:

import store from './store'
import RootState from './store/types'
import MyModuleState from './store/myModule/types'

// to get what you want typed how you want:
const myState = ((store.state as any).myModule as MyModuleState)

console.log(myState.testValue)

편집: 주(州)에 직접 접근하는 것이 문제인 것 같습니다.

const isAuthed = store.state.UserProfile.authed;

나는 이것이 이름 앞에 있기 때문에 일어나는 일이라고 믿는다.해결책은 getter를 만드는 것입니다.

const getters: GetterTree<ProfileState, RootState> = {

    user(state): User {
        return state.user
    }

};

그 후, 다음과 같이 액세스 할 수 있습니다.

store.getters['UserProfile/user']

또한 상태 데이터에 액세스할 때 getter를 사용하는 것도 고려해 주십시오.자세한 내용은 Getters를 참조하십시오.

언급URL : https://stackoverflow.com/questions/52863117/accessing-vuex-store-modules-state-inside-router-ts

반응형