解决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

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

相关推荐
Chloe.Zz38 分钟前
一篇入门Agent
开发语言·前端·javascript
silvamux_1 小时前
4款新模型商务邮件翻译横评:0.98到0.46
android·java·javascript
xiaobobo33301 小时前
Ubuntu 26.04环境下使用vim软件编辑文档的一些不常用用法
ubuntu·vim常用用法
定栓1 小时前
Webpack迁到Vite第六节:构建配置详解(vite.config.js)
前端·javascript·webpack
远离UE411 小时前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
RobinDevNotes11 小时前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
keyipatience11 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
SensorFlow15 小时前
曝光埋点别放在组件渲染里:连续可见与去重范围怎么验收
javascript
harris148154352975815 小时前
能解码不等于能信任:JWT 的签名到底验的是什么
javascript
liqingdi43715 小时前
[SWPUCTF 2023 秋季新生赛]Easy SMC
服务器·前端·javascript