This commit is contained in:
2025-07-09 20:36:32 +08:00
commit af33978d28
43 changed files with 9434 additions and 0 deletions

160
src/router/index.ts Normal file
View File

@ -0,0 +1,160 @@
/**
* Vue Router路由配置
*/
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../stores/modules/user'
// 路由元信息接口
export interface RouteMeta {
title?: string
icon?: string
hidden?: boolean
roles?: string[]
requireAuth?: boolean
keepAlive?: boolean
}
// 扩展RouteRecordRaw类型
declare module 'vue-router' {
interface RouteMeta {
title?: string
icon?: string
hidden?: boolean
roles?: string[]
requireAuth?: boolean
keepAlive?: boolean
}
}
// 静态路由
export const staticRoutes: RouteRecordRaw[] = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
meta: {
title: '首页',
icon: 'home'
}
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
meta: {
title: '关于',
icon: 'info'
}
},
{
path: '/login',
name: 'Login',
component: () => import('../views/Login.vue'),
meta: {
title: '登录',
hidden: true
}
},
{
path: '/404',
name: 'NotFound',
component: () => import('../views/404.vue'),
meta: {
title: '页面未找到',
hidden: true
}
}
]
// 需要登录的路由
export const authRoutes: RouteRecordRaw[] = [
{
path: '/dashboard',
name: 'Dashboard',
component: () => import('../views/Dashboard.vue'),
meta: {
title: '仪表板',
icon: 'dashboard',
requireAuth: true
}
},
{
path: '/admin',
name: 'Admin',
component: () => import('../views/Admin.vue'),
meta: {
title: '管理中心',
icon: 'admin',
requireAuth: true
}
},
{
path: '/profile',
name: 'Profile',
component: () => import('../views/Profile.vue'),
meta: {
title: '个人中心',
icon: 'user',
requireAuth: true
}
}
]
// 创建路由实例
const router = createRouter({
history: createWebHistory(),
routes: [
...staticRoutes,
...authRoutes,
// 404通配符路由
{
path: '/:pathMatch(.*)*',
redirect: '/404'
}
],
scrollBehavior(_, __, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
}
})
// 路由守卫
router.beforeEach((to, _, next) => {
const userStore = useUserStore()
// 检查是否需要认证
if (to.meta?.requireAuth) {
if (!userStore.isLoggedIn) {
// 未登录,跳转到登录页
next({
path: '/login',
query: { redirect: to.fullPath }
})
return
}
}
// 如果是登录页且已登录,跳转到首页
if (to.path === '/login' && userStore.isLoggedIn) {
next('/')
return
}
next()
})
// 路由错误处理
router.onError((error) => {
console.error('路由错误:', error)
})
export default router
// 工具函数 - 获取所有路由(用于菜单生成)
export const getAllRoutes = (): RouteRecordRaw[] => {
const allRoutes = [...staticRoutes, ...authRoutes]
return allRoutes.filter(route => !route.meta?.hidden)
}