From 96281ecf8361f670d94fd9fd55023108857a1c84 Mon Sep 17 00:00:00 2001 From: Songsl <2431955898@qq.com> Date: Sat, 25 Apr 2026 17:48:05 +0800 Subject: [PATCH] =?UTF-8?q?=E8=87=AA=E5=AE=9A=E4=B9=89=E6=8C=87=E4=BB=A4?= =?UTF-8?q?=E5=B0=81=E8=A3=85=EF=BC=8C=E5=88=B7=E6=96=B0=E7=A9=BA=E7=99=BD?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/router/index.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/router/index.ts b/src/router/index.ts index e58f7ab..3d7ef1c 100644 --- a/src/router/index.ts +++ b/src/router/index.ts @@ -69,10 +69,13 @@ const routes = [ }, ], }, - // { - // path: '/:pathMatch(.*)*', - // redirect: '/user/login', // 404 重定向到登录页,避免循环 - // }, + { + path: '/:pathMatch(.*)*', + redirect: () => { + const token = getStorage('token') + return token ? '/dashboard' : '/user/login' + }, // 404 重定向到登录页,避免循环 + }, ] const router = createRouter({ @@ -87,17 +90,17 @@ router.beforeEach(async (to, _from) => { const userStore = useUserStore() const isLoggedIn = !!userStore.token + console.log('dynamicRoutesReady', dynamicRoutesReady) + console.log('isLoggedIn', isLoggedIn) + console.log('to.meta.requiresAuth', to.meta.requiresAuth) + console.log('to.meta.isAuthPage', to.meta.isAuthPage) + // 1. 未登录访问需要认证的页 → 登录页 if (!isLoggedIn && to.meta.requiresAuth) { return '/user/login' } - // 2. 已登录访问登录/注册页 → 首页 - if (isLoggedIn && to.meta.isAuthPage) { - return '/' - } - - // 3. ✅ 动态路由恢复(只执行一次) + // 2. ✅ 动态路由恢复(只执行一次) if (isLoggedIn && !dynamicRoutesReady) { const menuList = getStorage('menusInfo') if (menuList?.length > 0) { @@ -107,10 +110,15 @@ router.beforeEach(async (to, _from) => { routeList.forEach((route) => router.addRoute('Layout', route)) dynamicRoutesReady = true // 返回目标路由以触发重新匹配 - return { ...to, replace: true } + return to.redirectedFrom?.fullPath || true } } + // 3. 已登录访问登录/注册页 → 首页 + if (isLoggedIn && to.meta.isAuthPage) { + return '/' + } + // 4. 其他情况正常放行 return true })