首页 文章

vue.js:路由保护等待异步值

提问于
浏览
0

和每个应用程序一样,我有几条路线 . 例如( router/index.js 摘录):

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

正如您在路径定义中所看到的,当访问 reporting 时,用户需要具有管理员权限,这是vuex存储中的属性 . 问题:这个属性是异步的,当初访问守卫时当然是假的 . 我怎样才能让我的警惕等待它?

守护:

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

1 回答

  • 2

    store.watch观看吸气器怎么样?

    假设如果尚未提取数据,则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('/');
    

相关问题