You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue-Router导航守卫无限重定向问题求助(权限拦截场景)

解决Vue Router无认证时无限重定向问题

问题场景

需求:无认证token时拦截页面并重定向至登录页,但当前代码触发无限重定向错误,错误提示如下:

[警告] [Vue Router warn]: 检测到导航守卫中存在无限重定向(从 "/" 跳转到 "/login")。为避免栈溢出已终止。若不修复,生产环境会崩溃。(vue-router.js, 第43行)
启动路由时发生意外错误:
Error: 导航守卫中存在无限重定向
(匿名函数) — vue-router.mjs:3178

现有代码文件:routes.ts 和 main.ts

错误原因

当前导航守卫未排除登录页面的检查逻辑:当无cookie时,会重定向到/login,但导航守卫会再次触发检查,此时依然无cookie,又会重复重定向到/login,形成无限循环。同时原守卫逻辑中,已认证时强制跳转到/,会覆盖用户原本想要访问的路由,不符合需求。

解决方案

1. 修正main.ts的导航守卫逻辑

修改导航守卫,排除登录页的检查,同时正确放行已认证的路由请求:

import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import routes from './routes';

// 修正导出函数的错误写法
export default function createRouterInstance() {
  const Router = createRouter({
    // 补充history模式,示例用hash模式,可按需替换为createWebHistory
    history: createWebHashHistory(),
    routes
  });
  
  Router.beforeResolve(async(to, from, next) => {
    // 1. 如果目标路由是登录页,直接放行
    if (to.path === '/login/') {
      return next();
    }

    // 2. 检查是否有认证凭证(假设token存在于cookie中,可根据实际存储方式调整)
    const hasToken = document.cookie.includes('token'); // 替换为你的token判断逻辑
    if (!hasToken) {
      // 无凭证时重定向到登录页,记录当前路由方便登录后跳转回来
      return next({ path: '/login/', query: { redirect: to.fullPath } });
    }

    // 3. 有凭证时正常放行
    next();
  });

  return Router;
}

2. (可选)优化路由配置(routes.ts)

给需要认证的路由添加meta字段,让权限控制更灵活:

import { RouteRecordRaw } from 'vue-router';
const routes: RouteRecordRaw[] = [
  {
    path: '/login/',
    name: 'Login',
    component: () => import('layouts/LoginLayout.vue')
  },

  {
    path: '/',
    component: () => import('layouts/DVRLayout.vue'),
    meta: { requiresAuth: true }, // 标记该路由需要认证
    children: [
      { path: 'dashboard', component: () => import('pages/DashboardPage.vue') },
      { path: 'settings', component: () => import('pages/AppSettings.vue')},
    ],
  },

  {
    path: '/:catchAll(.*)*',
    component: () => import('pages/ErrorNotFound.vue'),
  },
];
export default routes;

对应修改main.ts中的守卫逻辑,基于meta判断:

Router.beforeResolve(async(to, from, next) => {
  // 登录页直接放行
  if (to.path === '/login/') {
    return next();
  }

  // 检查目标路由是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth) {
    const hasToken = document.cookie.includes('token');
    if (!hasToken) {
      return next({ path: '/login/', query: { redirect: to.fullPath } });
    }
  }

  next();
});

3. 登录页跳转回原路由(可选)

登录成功后,可根据redirect参数跳转回用户原本想要访问的页面:

// 登录页组件示例
const router = useRouter();
const route = useRoute();

// 登录成功后
const handleLoginSuccess = () => {
  const redirect = route.query.redirect as string || '/dashboard';
  router.push(redirect);
};

内容的提问来源于stack exchange,提问作者Alex Dalen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:35:12