数字督察一体化平台-前端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

95 lines
3.0 KiB

import { createRouter, createWebHashHistory, type RouteRecordRaw, RouterView } from 'vue-router'
import { routes, LAYOUT } from './routes'
import { MenuEnum } from '@/enums/appEnums'
import { de } from 'element-plus/es/locale'
// 匹配views里面所有的.vue文件,动态引入
const modules = import.meta.glob('/src/views/**/*.vue')
export function getModulesKey() {
return Object.keys(modules).map((item) => item.replace('/src/views/', '').replace('.vue', ''))
}
function normalizeUrl(url: string) {
if (/^https?:\/\//i.test(url)) return url
return "https://" + url
}
function genExternalPath(menu: any) {
return `/external/${menu.id}`
}
export function createRouteRecord(menus) {
return menus.map(menu => {
const isExternal = !!menu.openOutside
console.log("============menu==============")
console.log(menu)
const routeRecord: RouteRecordRaw = {
// ✅ 外链用站内 path,占位
path: isExternal ? genExternalPath(menu) : menu.paths,
// ✅ name 用字符串,别用 Symbol
name: isExternal ? `external-${menu.id ?? menu.menuName}` : (menu.name ?? menu.paths),
meta: {
hidden: !menu.isShow,
keepAlive: !!menu.isCache,
title: menu.menuName,
perms: menu.perms,
icon: menu.icon,
type: menu.menuType,
openOutside: menu.openOutside,
openNewPage: menu.openNewPage,
// ✅ 把真正外链放到 meta.url
url: isExternal ? normalizeUrl(menu.paths) : undefined,
},
// ✅ 外链用一个固定组件
component: isExternal
? () => import("@/views/ExternalLink.vue")
: (menu.menuType === MenuEnum.CATALOGUE ? LAYOUT : loadRouteView(menu.component)),
}
if (menu.children?.length) {
routeRecord.children = createRouteRecord(menu.children)
}
return routeRecord
})
}
// 动态加载组件
function loadRouteView(component: string) {
try {
const key = Object.keys(modules).find((key) => {
return key.includes(`${component}.vue`)
})
if (key) {
return modules[key]
}
throw Error(`找不到组件${component},请确保组件路径正确`)
} catch (error) {
console.error(error)
return RouterView
}
}
// 找到第一个有效的路由
export function findFirstValidRoute(routes: RouteRecordRaw[]): string | undefined {
for (const route of routes) {
if (route.meta?.type == MenuEnum.MENU && !route.meta?.hidden) {
return route.name as string
}
if (route.children) {
const name = findFirstValidRoute(route.children)
if (name) {
return name
}
}
}
}
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router;