最初
ts
const viewFiles = import.meta.glob('@/views/**/*.vue')
export function loadView(filePath: string) {
const key = `@/${filePath}`
return viewFiles[key]
}
export function formatAsyncRoutes(menuList: any[]) {
return menuList.map(menuItem => {
return {
path: menuItem.path,
meta: menuItem.meta || {},
component: () => import('@/layout/index.vue'),
children: menuItem.children.map(child => ({
path: child.path,
meta: child.meta || {},
component: loadView(child.component)
}))
}
})
}
解决
ts
// 获取所有views下vue文件,拿到真实绝对路径key
const viewModules = import.meta.glob('/src/views/**/*.vue')
export function loadView(filePath: string) {
// 后端传入:views/tableDemo/index.vue
// 拼接成真实的key:/src/views/tableDemo/index.vue
const realPath = `/src/${filePath}`
return viewModules[realPath]
}
export function formatAsyncRoutes(menuList: any[]) {
return menuList.map(menu => {
return {
path: menu.path,
meta: menu.meta || {},
component: () => import('@/layout/index.vue'),
children: menu.children.map(child => ({
path: child.path,
meta: child.meta || {},
component: loadView(child.component)
}))
}
})
}
@ 只是 vite 的别名标识,运行时 import.meta.glob 不会识别别名,只识别真实文件物理路径 /src/xxx
这是绝大多数人动态路由页面加载失败的最隐蔽原因