IT이야기

내 경로에서 Vue'x getter를 사용할 때 "state.user가 null임"

cyworld 2022. 5. 2. 21:23
반응형

내 경로에서 Vue'x getter를 사용할 때 "state.user가 null임"

나는 VueJS에 익숙하지만 Vuex에 대해서는 거의 알지 못한다.

기본적으로 역할 기반 라우터 시스템을 설정하고 싶다: JSON my API returns는 사용자 역할이 포함된 어레이를 포함하는 개체로, Vue에서 구문 분석할 수 있도록 문자열화한다.

몇 가지 튜토리얼을 따라 했고, 몇 가지 수정 후에 내 가게의 모양(관련 부분):

getters: {
    isLogged: state => !!state.user,

    roles: state => JSON.parse(state.user.user.roles) // returns ['authenticated_user', 'admin']
}

만약 내가 'roles' getter를 테스트한다면mapGetter구성 요소 내에서 데이터를 가져오는 데 문제가 없을 겁니다.하지만, 나는 계속해서state.user is null내 콘솔에 오류로 표시됨.

설정 방법은 다음과 같다.

const routes = [
    ...
    {
        path: '/admin',
        name: 'admin',
        component: () => import('../admin/Dashboard'),
        meta: {
            auth: true,
            role: 'admin'
       }
    },
    ...

];

router.beforeEach((to, from, next) => {
    const loggedIn = localStorage.getItem('user');
    const role = store.getters.roles;
    console.log(store.getters.roles); // state.user is null

    if (to.matched.some(record => record.meta.auth) && !loggedIn) {
        next('/login');
        return;
    }

    if (loggedIn && to.match.some(record => !roles.includes(record.meta.role)) {
        next(from.fullPath);
        return;
    }

    next();
});

내 상황과 가장 가까운 질문을 찾았지만 도움이 되지 않았다. 왜냐하면 부에가 인정하는 것 같았기 때문이다.state.user내 경우에는

제가 무엇을 빠뜨리고 있나요?

미리미리 고마워

역할 변경에 필요한 항목 변경:roles: state => state.user && JSON.parse(state.user.user.roles)

먼저 state.user가 있는지 확인한 다음 값을 가져오십시오.

참조URL: https://stackoverflow.com/questions/61051210/state-user-is-null-when-using-vuex-getter-in-my-routes

반응형