要求用户在一个角色中,并在路由中登录



我有一个路由

{
path: '/flights_marketers/dashboard',
name: 'flights_marketers/dashboard',
meta: { title: 'Flights Marketers Dashboard',requiresAuth: true, rolesAllowed: 'guest,admin,marketer' },
component: () => import( '../views/backendviews/flights_marketers/flights_marketers_dashboard.vue')
},

要求用户登录,如果用户没有登录,则用户被重定向到登录页面,如果已登录但没有所需的角色,则重定向到未授权访问页面。

检查用户是否已登录

router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (store.state.auth.loggedin_status == 'loggedin') {

next();
return;
}
window.location.replace("/Login");
} else {
next();
}
});

和这个不工作

router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.matched.some((record) => record.meta.requiresAuth)) {
if (store.state.auth.loggedin == 'loggedin' && to.meta.rolesAllowed.split(',').includes(store.state.auth.role) ) {

next();
return;
}
else{
window.location.replace("/Unauthorized");
}
window.location.replace("/Login");
} else {
next();
}
});

检查已登录的用户是否具有所需的角色并已登录。我怎样才能纠正这个问题?

next({ path, replace: true })代替window.location.replace:

// window.location.replace("/Unauthorized");
next({ path: "/Unauthorized", replace: true });
// window.location.replace("/Login");
next({ path: "/Login", replace: true });

你的beforeEach回调的逻辑应该类似于这个伪代码:

if (/* route requires auth */) {
if (/* logged in */) {
if (/* authorized */) {
return next()
} else {
return next({ path: '/Unauthorized', replace: true })
}
} else {
return next({ path: '/Login', replace: true })
}
} else {
return next()
}

演示

最新更新