programing

vue.js: 루트 가드가 비동기 값을 기다립니다.

bestcode 2022. 8. 25. 23:55
반응형

vue.js: 루트 가드가 비동기 값을 기다립니다.

모든 어플리케이션과 마찬가지로 몇 가지 루트가 있습니다.예를 들어 (router/index.js발췌):

[{
    path: '/reporting',
    name: 'Reporting',
    component: reporting,
    meta: {
        adminOnly: true
    }
},
...]

루트 정의에서 알 수 있듯이 에 액세스 할 때reporting사용자에게 vuex 저장소의 속성인 관리자 권한이 있어야 합니다.문제:이 속성은 비동기이며 가드에서 처음 액세스할 때는 물론 false입니다.어떻게 하면 방심하지 않고 기다리게 할 수 있을까요?

가드:

if (to.matched.some(route => route.meta.adminOnly)) {
    if (store.getters.userInfo.isAdmin) {
        next()
    } else {
      next('/')
    }
} else {
    next()
}

가게를 이용하는 게터를 보는 건 어때?보실래요?

당신의 getter가 돌아왔다고 가정하면null데이터를 아직 가져오지 않은 경우.

if (store.getters.userInfo.isAdmin === null) {
    const watcher = store.watch(store.getters.userInfo.isAdmin, isAdmin => {
        watcher(); // stop watching
        if (isAdmin) next();
        else next('/');
    });
}
else if (store.getters.userInfo.isAdmin) next();
else next('/');

언급URL : https://stackoverflow.com/questions/45479496/vue-js-route-guard-wait-for-async-value

반응형