等待 vuejs 路由器的状态更新之前输入



我想限制对vue路由器中某些页面的访问。例如,我宁愿在需要的子路由中进行"hasUserAccess"检查,而不是在每个组件中都有auth逻辑

{
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"页面时,这将按预期工作。当我手动键入/admin url(或在管理页面上按f5(时,这是不起作用的,因为用户对象还没有从服务器中提取(其他一些逻辑负责提取用户(。"beforeEnter"是异步的,但据我所知,不可能从路由器"监视"或等待用户对象,因为路由器不是典型的vue组件。

那么,这个常见的问题通常是如何解决的呢?

只需将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();
});

在你方便的时候试着修改一下,但在你这样的情况下,我或多或少会这样做。

最新更新