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