import { createRouter, createWebHistory } from 'vue-router' import { useAuthStore } from '@/stores/auth' import HomeView from '../views/HomeView.vue' import LoginView from '../views/LoginView.vue' import ProfileView from '../views/ProfileView.vue' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'home', component: HomeView, meta: { requiresAuth: true }, }, { path: '/login', name: 'login', component: LoginView, meta: { requiresAuth: false }, }, { path: '/profile', name: 'profile', component: ProfileView, meta: { requiresAuth: true }, }, { path: '/:pathMatch(.*)*', redirect: '/', }, ], }) // 路由守卫 router.beforeEach(async (to, from, next) => { const authStore = useAuthStore() const isAuthed = authStore.isAuthenticated if (to.meta.requiresAuth && !isAuthed) { next('/login') return } // 对受保护页面,若即将过期,尝试静默刷新一次(不强制等待,可选:等待) if (to.meta.requiresAuth && authStore.isAccessTokenExpiringSoon && authStore.isAccessTokenExpiringSoon()) { try { await authStore.refreshAccessToken() } catch { next('/login') return } } if (to.path === '/login' && isAuthed) { next('/') return } next() }) export default router