vue3+vite根据后端数据路径动态引入组件打包后加载失败
·
需求分析
根据网络请求到的路径加载对应路径下的组件。
结果
开发环境下,直接使用import方法传入后端返回的路径动态加载组件,结果正常访问和加载。但是打包后访问报错:TypeError: Failed to fetch dynamically imported module:https://xxx/xxx/index.vue
解决
可以使用Vite提供 的import.meta.glob 函数,预先声明可能动态加载的组件,让构建工具提前处理这些路径。
我把需要动态引入的组件统一放在一个路径下的,到时候根据请求到的文件夹名称拼接成完整路径访问。
<template>
<component v-if="AsyncComponent" :is="AsyncComponent"></component>
</template>
<script setup>
import { shallowRef } from 'vue';
// 预声明动态组件
const components = import.meta.glob('/src/components/formComponent/**/index.vue');
const AsyncComponent = shallowRef(null);
const loadComponent = async () => {
try {
// 动态加载组件(路径按实际业务逻辑获取)
const componentPath = 'test'; // 假设请求 API 获取
const module = await components[`/src/components/formComponent/${componentPath}/index.vue`]();
AsyncComponent.value = module.default;
} catch (err) {
console.error('加载组件失败:', err);
}
};
loadComponent();
</script>
更多使用方法和解释参考:功能 | Vite 官方中文文档
暂时想到的解决方法就这一个,其他的还没研究。
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐


所有评论(0)