为了避免无限重定向,可以通过添加一个条件来中断重定向的循环。例如,可以在路由导航守卫中添加一个判断条件,如果当前路由和目标路由相同,则不进行重定向。

下面是一个示例代码:

// 前置导航守卫
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 (to.path === from.path) {
      next();
    } else {
      if (rolesLocal === "admin") {
        next("/home");
      } else if (rolesLocal === "teacher") {
        next("/teacherhome");
      } else if (rolesLocal === "user") {
        next("/userhome");
      } else {
        next();
      }
    }
  }
})

通过添加if (to.path === from.path)的判断条件,可以判断当前路由和目标路由是否相同。如果相同,则不进行重定向,直接调用next()进行路由的正常跳转。这样可以避免无限重定向的问题

前置导航守卫routerbeforeEachasync to from next = const token = localStoragegetItemtoken; const rolesLocal = sessionStoragegetItemroles; const requiresAuth = tometarequiresAuth; const roles = tometarole

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

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