Vue Router beforeEach 导致无限重定向的解决方法
Vue Router beforeEach 导致无限重定向的解决方法
在使用 Vue Router 的 beforeEach 钩子函数进行路由守卫时,可能会遇到无限重定向的问题。本文将分析导致无限重定向的常见原因,并提供解决方案。
问题分析
以下代码片段展示了一个常见的 beforeEach 钩子函数实现,用于根据用户角色进行路由跳转:
router.beforeEach(async (to, from, next) => {
const token = localStorage.getItem('token');
const rolesLocal = sessionStorage.getItem('roles');
const requiresAuth = to.meta.requiresAuth;
const roles = to.meta.roles;
// 如果该路由有权限且未登录,则跳转登录页面
if (requiresAuth && !token && !roles) {
alert('请先登录!');
if (to.path === '/login') { // 如果当前路由是登录页面,则放行
next();
} else {
next('/login');
}
} else {
if (rolesLocal === 'admin' && rolesLocal !== 'teacher' && rolesLocal !== 'user') {
next('/home');
} else if (rolesLocal !== 'admin' && rolesLocal === 'teacher' && rolesLocal !== 'user') {
next('/teacherhome');
} else if (rolesLocal !== 'admin' && rolesLocal !== 'teacher' && rolesLocal === 'user') {
next('/userhome');
} else {
next();
}
}
})
此代码会导致无限重定向的原因是在判断用户角色时存在错误。
在 if 条件判断中,应该使用 === 而不是 !==。此外,每个条件应该使用 || 来判断,而不是 &&。因此,将代码中的 !== 改为 ===,将 && 改为 ||,以正确判断用户角色。修改后的代码如下所示:
router.beforeEach(async (to, from, next) => {
const token = localStorage.getItem('token');
const rolesLocal = sessionStorage.getItem('roles');
const requiresAuth = to.meta.requiresAuth;
const roles = to.meta.roles;
// 如果该路由有权限且未登录,则跳转登录页面
if (requiresAuth && !token && !roles) {
alert('请先登录!');
if (to.path === '/login') { // 如果当前路由是登录页面,则放行
next();
} else {
next('/login');
}
} else {
if (rolesLocal === 'admin' || rolesLocal === 'teacher' || rolesLocal === 'user') {
next();
} else {
next('/home'); // 默认跳转到 home 页面
}
}
})
解决方案
- 使用
===运算符进行严格比较: 确保角色判断逻辑准确,避免因类型转换而导致错误。 - 使用
||运算符判断多个角色: 当用户拥有多个角色时,应该使用||运算符进行判断,以确保能够正确跳转到对应页面。
总结
通过修改角色判断逻辑,可以避免 Vue Router beforeEach 钩子函数导致的无限重定向问题。在使用 beforeEach 钩子函数时,务必仔细检查代码逻辑,确保能够正确判断用户角色,并进行相应的路由跳转。
原文地址: https://www.cveoy.top/t/topic/pRlV 著作权归作者所有。请勿转载和采集!