解决Vue3 + TypeScript + Vite搭建的项目,动态路由页面加载失败的最隐蔽原因

最初

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

这是绝大多数人动态路由页面加载失败的最隐蔽原因

相关推荐
Penge6662 小时前
《Go 后端开发者学 TypeScript:数组和元组》
javascript
Penge6662 小时前
《Go 后端开发者学 TypeScript:export关键字大全》
javascript
Penge6662 小时前
《Go 后端开发者学 TypeScript:从零理解 async、await 与 Promise》
javascript
Penge6663 小时前
typescript 中const用法
javascript
theMuseCatcher4 小时前
Vue3评论(Comment)
typescript·vue3
Linux-lucky5 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
禁默5 小时前
启元 Q1 二次开发实践:Ubuntu 部署与仿真验证,从 PrimeConsole 到 ROS 2 Humble + RViz
linux·运维·ubuntu
skywalk81635 小时前
把 去也网站 从 Ubuntu 搬到 FreeBSD:一次 Service Jail + nginx 的部署实录
linux·运维·nginx·ubuntu·freebsd
afumu11 小时前
把五个网页版 AI 拉进同一个群聊:不用 API key 的多 Agent 编排
人工智能·chrome·typescript
程序员大阳13 小时前
HTML+CSS+JS对话式实战(3)-活动管理页实现查询、新增、删除API后端接口
javascript·css·html·实战·删除·查询·新增