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

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

相关推荐
前鼻音太阳熊1 小时前
【MES系统】- 工业HMI状态机可视化实践:从手写SVG到Cytoscape.js的技术选型与踩坑
开发语言·javascript·ecmascript
晓得迷路了2 小时前
栗子前端技术周刊第 139 期 - Nuxt 4.5、Vue 3.6 RC、Angular 发布节奏...
前端·javascript·vue.js
其实防守也摸鱼2 小时前
镜像校验完成iso完整操作流程(Windows 环境,适配 Ubuntu 22.04 / 24.04)
linux·服务器·windows·学习·ubuntu·教程
এ慕ོ冬℘゜2 小时前
原生 select 下拉框搜索失效踩坑:文本搜索与 ID 匹配不对应问题排查
前端·javascript·html
mayaairi12 小时前
JS循环语句深度解析:嵌套for、while与do...while
开发语言·前端·javascript
To_OC12 小时前
啃完流式输出:从一个卡顿的 LLM 接口开始,我搞懂了数据流到底怎么 “流”
前端·javascript·llm
一叶龙洲15 小时前
向日葵远程Ubuntu,支持隐私屏
linux·运维·ubuntu
海上彼尚15 小时前
Nodejs也能写Agent - 22.LangGraph篇 - 上下文工程
前端·javascript·人工智能·langchain·node.js
寒水馨16 小时前
Linux下载、安装llama.cpp-b10068(附安装包llama-b10068-bin-ubuntu-vulkan-x64.tar.gz)
linux·ubuntu·llm·llama·本地部署·llama.cpp·推理引擎