import { createRouter, createWebHistory } from 'vue-router' 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((to, from, next) => { const isAuthenticated = localStorage.getItem('token') // 简单的认证检查 if (to.meta.requiresAuth && !isAuthenticated) { // 需要认证但未登录,重定向到登录页 next('/login') } else if (to.path === '/login' && isAuthenticated) { // 已登录用户访问登录页,重定向到主页 next('/') } else { next() } }) export default router