import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/utils/router_menu' import { useAuthStore } from '@/stores/auth' const router = createRouter({ history: createWebHistory(), routes, }) // 受保护页面必须先通过服务端校验才渲染: // 本地 token 存在不代表有效(可能已过期/被重置),若只查 localStorage, // 页面会先渲染约 1 秒、等 /profile 返回 401 后才被踢回登录页。 router.beforeEach(async (to) => { const requiresAuth = to.matched.some(record => record.meta.requiresAuth) if (!requiresAuth) return true const authStore = useAuthStore() if (!authStore.token) { return { path: '/login', query: { redirect: to.fullPath } } } // 有 token 但还没加载用户信息时,先向服务端确认身份,失败则不得进入 if (!authStore.user) { try { await authStore.getProfile() } catch { authStore.clear() return { path: '/login', query: { redirect: to.fullPath } } } } // 管理后台仅对 role >= 10 开放 if (to.matched.some(record => record.meta.requiresAdmin) && (authStore.user?.role ?? 0) < 10) { return '/dashboard/overview' } return true }) export default router