使用import.meta.url实现传递路径动态加载资源

背景

在开发 Vue 项目时,动态路由是必要功能,从后端或本地获取到菜单列表的 component 都是是字符串,要转成动态加载方式。因为项目用到了 monorepo,有多个子模块,但有的子模块是直接被引用的,不会单独打包,没有 vite.config.ts 配置,也就没有 @ 别名,转换路由的功能又抽成公共函数,这时模块路径就不好处理,因为动态导入路径默认是相对当前模块的。从别名设置处获得灵感,使用 import.meta.urlimport.meta.url 返回当前模块的完整 URL,在调用的地方把 import.meta.url 当作参数传递给转换路由的函数,这样在函数中就可以得到该子模块的相对路径了,相当于传递了相对路径。

示例

调用处

typescript 复制代码
setAsyncRouter(import.meta.url, 'monitor')

转换函数

typescript 复制代码
const setAsyncRouter = (path: string, module: string) => {
		const menuStore = useMenuStore();
		const baseUrl = new URL("./", path).href;
		const baseRouter: any[] = [
			{
				path: `/${module}`,,
				name: "layout",
				component: "views/layout/index.vue",
				meta: {
					title: "底层layout",
				},
				children: [],
			},
		];
		const menus = menuStore.asyncMenus;
		const asyncRouter = getMenuList(menus, module););
		baseRouter[0].children = asyncRouter;
		asyncRouterHandle(baseRouter, baseUrl);
	};
typescript 复制代码
function asyncRouterHandle(asyncRouter: Router[], path: string) {
	asyncRouter.forEach((item) => {
		if (item.component) {
			const component = `${path}${item.component}`;
			item.component = () => import(component); // 这里要先定义变量再用
		}
		if (item.children) {
			asyncRouterHandle(item.children, path);
		}
	});
}

需要传递路径的地方都可以这么用。

相关推荐
qq_419854056 小时前
空间网格管理器
前端·javascript·html
qingmiaozhuan6 小时前
电脑录屏没有声音还能补救吗?音频采集链路详解及4种技术方案
前端·电脑·音视频·开发工具·电脑录屏·电脑录屏软件
天若有情6736 小时前
Dev_Portfolio 个人主页html网页源码分享!!!
前端·html·源码·个人主页
李剑一6 小时前
ant-design-vue 1.x 版本换肤功能开发
前端·vue.js·ant design
京东云开发者6 小时前
【Coding生态】从代码托管到 AI 能力底座:与Coding一起共建 AI 研发生态
前端
guhy fighting7 小时前
x-www-form-urlencoded,form-data,raw 表单请求格式的区别
前端·表单请求格式
李明卫杭州7 小时前
Vue2 与 Vue3 自定义指令详解:钩子变化、迁移指南与实战示例
前端·javascript·vue.js
问商十三载7 小时前
大模型GEO内容更新频率:3个节奏规律提收录权重,零成本提30%引用率附更新计划表
前端·人工智能·机器学习
yingyima7 小时前
sed 命令速查手册:从一次午夜事故说起
前端
七月丶7 小时前
线上出 Bug,你还在让用户"清一下缓存"?我用一个插件让每个请求自报版本
前端·javascript·面试