<template>
<div>
<component v-for="(component, name) in dynamicComponents" :key="name" :is="component" />
<div></div>
<component :is="singleCom"></component>
</div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, markRaw } from "vue";
const dynamicComponents = reactive({});
let singleCom = ref();
onMounted(async () => {
const modules = import.meta.glob("./components/importXX-*.vue");
for (const path in modules) {
const module = await modules[path]();
const componentName = path.replace(/^\.\/components\/(.*)\.vue$/, "$1");
console.log(`componentName`, componentName);
dynamicComponents[componentName] = markRaw(module.default);
}
singleCom.value = await getDynamicCom("./components/importXX-two.vue");
});
const getDynamicCom = async (path: string) => {
let tempRes = () => import(new URL(path, import.meta.url).href);
let tempXX = await tempRes();
return tempXX["default"];
};
</script>
<style lang="scss" scoped></style>
【vue3+ts】组件内部的按需引入两种方案(单个,批量)处理
于 2024-06-04 18:46:19 首次发布