Vue Router 前置导航守卫无限重定向问题解决方法

在使用 Vue Router 的前置导航守卫时,可能会遇到无限重定向的问题。本文将详细介绍该问题产生的原因以及解决方法。

问题分析

假设您的代码如下:

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('请先登录!'); 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(); } } });

根据代码逻辑分析,当用户未登录且需要权限时,会跳转到登录页面。但是在登录页面,又会执行前置导航守卫,由于用户仍未登录,所以又会跳转到登录页面,形成了无限循环重定向的问题。

解决方法

为了解决这个问题,可以在前置导航守卫中添加一个判断条件,如果当前路由是登录页面,就直接放行,不再跳转。修改代码如下:

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

这样修改后,当用户未登录且需要权限时,会跳转到登录页面,但是在登录页面,不会再次执行前置导航守卫,从而避免了无限循环重定向的问题。

总结

本文介绍了 Vue Router 前置导航守卫无限重定向问题产生的原因以及解决方法。通过添加判断条件,在登录页面放行,避免了无限循环重定向的问题。

原文地址: https://www.cveoy.top/t/topic/pRlJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录