WEB/src/router/index.ts
2026-03-20 09:03:44 +08:00

236 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createRouter, createWebHistory, RouterView } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { getToken } from '@/utils/auth'
import Layout from '@/layout/index.vue'
import { usePermissionStore } from '@/stores/modules/permission'
import { h } from 'vue'
import { componentMap } from './map'
/**
* 空白父级路由组件
*/
const ParentView = {
name: 'ParentView',
render: () => h(RouterView)
}
/**
* 基础路由 - 固定不变的路由
*/
export const constantRoutes: RouteRecordRaw[] = [
{
path: '/redirect',
component: Layout,
meta: { hidden: true },
children: [
{
path: '/redirect/:path(.*)',
component: () => import('@/views/redirect/index.vue')
}
]
},
{
path: '/login',
name: 'Login',
component: () => import('@/views/login/index.vue'),
meta: { title: '登录', hidden: true }
},
{
path: '/admin/land',
name: 'AdminLand',
component: () => import('@/views/admin/land/index.vue'),
meta: { title: '语言翻译', hidden: true }
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index.vue'),
meta: {
title: 'Dashboard',
icon: 'dashboard',
affix: true
}
}
]
},
{
path: '/message',
component: Layout,
meta: { hidden: true },
children: [
{
path: '',
name: 'Message',
component: () => import('@/views/message/index.vue'),
meta: {
title: '消息中心',
icon: 'example',
affix: false
}
}
]
},
{
path: '/profile',
component: Layout,
meta: { hidden: true },
children: [
{
path: '',
name: 'Profile',
component: () => import('@/views/profile/index.vue'),
meta: {
title: '个人中心',
icon: 'user',
affix: false
}
}
]
},
{
path: '/download',
component: Layout,
meta: { hidden: true },
children: [
{
path: '',
name: 'Download',
component: () => import('@/views/download/index.vue'),
meta: {
title: '下载中心',
icon: 'link',
affix: false
}
}
]
}
]
/**
* 404路由配置
*/
export const notFoundRoute: RouteRecordRaw = {
path: '/:pathMatch(.*)*',
redirect: '/404',
meta: { hidden: true }
}
export const notFoundPage: RouteRecordRaw = {
path: '/404',
name: 'Page404',
component: () => import('@/views/404.vue'),
meta: { hidden: true }
}
/**
* 解析组件路径
*/
function resolveComponent(componentPath: string) {
if (componentMap[componentPath]) {
return componentMap[componentPath]
}
console.warn(`Component ${componentPath} not found in componentMap, using dynamic import`)
// 处理常见的目录结构,例如 'warehouse' -> 'warehouse/index.vue'
if (!componentPath.includes('/')) {
return () => import(`@/views/${componentPath}/index.vue`).catch(() => import(`@/views/${componentPath}.vue`))
}
return () => import(`@/views/${componentPath}.vue`)
}
/**
* 将菜单数据转换为路由格式
*/
export const transformMenusToRoutes = (menus: any[]) => {
if (!menus || !Array.isArray(menus)) {
return []
}
const transformRoute = (menu: any, parentName?: string): RouteRecordRaw => {
let routeName = menu.name
// 检查名称冲突:如果子路由名称与父路由名称相同,Vue Router 4 会报错
if (routeName && parentName && routeName === parentName) {
routeName = `${routeName}_Child`
console.warn(`Route name conflict detected: ${parentName}. Child name changed to ${routeName}`)
}
let routePath = menu.path
const isExternal = /^(https?:|mailto:|tel:)/.test(routePath || '')
// Vue Router 4 要求顶层路由路径必须以 / 开头
if (!parentName && routePath && !routePath.startsWith('/') && !isExternal) {
routePath = `/${routePath}`
}
const route: any = {
path: routePath,
name: routeName,
hidden: !!menu.hidden,
alwaysShow: !!menu.alwaysShow,
meta: {
title: menu.meta?.title || menu.name || '',
icon: menu.meta?.icon || '',
noCache: !!menu.meta?.noCache,
affix: !!menu.meta?.affix,
breadcrumb: menu.meta?.breadcrumb !== false,
activeMenu: menu.meta?.activeMenu,
roles: menu.meta?.roles
}
}
if (menu.redirect) {
route.redirect = menu.redirect
}
if (menu.component) {
if (menu.component === 'Layout') {
route.component = Layout
} else if (typeof menu.component === 'string') {
// 正常情况:字符串类型
if (menu.component.startsWith('@/views/')) {
const componentPath = menu.component.replace('@/views/', '')
route.component = resolveComponent(componentPath)
} else if (menu.component.startsWith('@/')) {
const componentPath = menu.component.replace('@/', '')
route.component = () => import(`@/${componentPath}.vue`)
} else {
route.component = resolveComponent(menu.component)
}
} else {
// 如果后端传回的 component 是一个带有 __file 等不该出现的打包后的对象
// 通过父子路径拼接去 map 里面找,或者直接截取 path
const fallbackPath = parentName ? `${parentName.toLowerCase()}/${menu.path}` : menu.path;
console.warn(`Invalid component format for path [${menu.path}]. Falling back to use componentMap key: ${fallbackPath}`);
route.component = resolveComponent(fallbackPath);
}
} else {
if (!menu.children || menu.children.length === 0) {
route.component = ParentView
} else {
route.component = Layout
}
}
if (menu.children && menu.children.length > 0) {
route.children = menu.children.map((child: any) => transformRoute(child, routeName))
}
return route as RouteRecordRaw
}
return menus.map(menu => transformRoute(menu))
}
const router = createRouter({
history: createWebHistory('/'),
routes: constantRoutes,
scrollBehavior: () => ({ top: 0 })
})
export default router