import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router' import { useUserStore } from '@/store/user' const routes: RouteRecordRaw[] = [ { path: '/', redirect: '/dashboard' }, { path: '/login', name: 'login', component: () => import('@/views/login/index.vue'), meta: { public: true, title: '登录' }, }, { path: '/dashboard', name: 'dashboard', component: () => import('@/views/dashboard/index.vue'), meta: { title: '首页' }, }, // 未匹配路由回首页;若未登录会被守卫拦到登录页 { path: '/:pathMatch(.*)*', redirect: '/dashboard' }, ] const router = createRouter({ history: createWebHistory(), routes, }) /** * 全局前置守卫。 * * 三层判断: * 1. `meta.public` 标记的页面(登录页)直接放行 * 2. 无令牌 → 跳登录页,并把原目标记在 query 里供登录后回跳 * 3. 有令牌但内存中无用户信息(说明是刷新页面)→ 调 /me 恢复会话; * 失败则视为令牌已失效,清状态并跳登录页 */ router.beforeEach(async (to) => { const userStore = useUserStore() if (to.meta.public) { return true } if (!userStore.token) { return { path: '/login', query: { redirect: to.fullPath } } } if (!userStore.userInfo) { try { await userStore.fetchUserInfo() } catch { userStore.resetAuth() return { path: '/login', query: { redirect: to.fullPath } } } } return true }) router.afterEach((to) => { const title = to.meta.title as string | undefined document.title = title ? `${title} - ${import.meta.env.VITE_APP_TITLE}` : import.meta.env.VITE_APP_TITLE }) export default router