【问题标题】:Wait for state update in vuejs router´s beforeEnter在 vuejs 路由器的 beforeEnter 中等待状态更新
【发布时间】:2021-07-27 23:29:06
【问题描述】:

我想限制对我的 vue 路由器中某些页面的访问。例如,我宁愿在我的子路由中需要它的地方进行“hasUserAccess”检查,而不是在每个组件中都有身份验证逻辑

{
    path: 'admin',
    name: 'admin',
    beforeEnter: hasUserAccess,
    component: () => import(/* webpackChunkName: "admin" */ '@/_ui/admin/Admin.vue')
},

...

function hasUserAccess(to, from, next) {
    if (myState.user.isAdmin) {
        next();
    } else {
        next({ path: '/noaccess' });
    }
}

当从另一个页面导航到“管理”页面时,这将按预期工作。当我手动输入 /admin url(或在管理页面上按 f5)时,这不起作用,因为尚未从服务器获取用户对象(一些其他逻辑正在处理获取用户)。 “beforeEnter”是异步的,但据我所知,由于路由器不是典型的 vue 组件,因此无法从路由器“观察”或等待用户对象。

那么这个常见的问题一般是怎么解决的呢?

【问题讨论】:

  • 从路由器获取用户?
  • 是的,这是一个解决方案,但如前所述,其他一些逻辑正在解决这个问题,我想避免更改该逻辑。

标签: vue.js vue-router


【解决方案1】:

只需将beforeEach 应用于路由器本身。在路由器文件上,您可以这样做:

router.beforeEach((to, from, next) => {
  //in case you need to add more public pages like blog, about, etc
  const publicPages = ["/login"]; 
  //check if the "to" path is a public page or not
  const authRequired = !publicPages.includes(to.path); 

  //If the page is auth protected and hasUserAccess is false
  if (authRequired && !hasUserAccess) {
    //return the user to the login to force the user to login
    return next("/login"); 
  }
  //The conditional is false, then send the user to the right place
  return next();
});

尝试在您方便的时候修改它,但这或多或少是我在像您这样的情况下所做的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多