vue3+vite动态引入组件

1,161 阅读1分钟

1.假如我们有一个需求,需要引入这个文件夹的组件,传统的做法是一个个import去引入组件。

image.png

2.现在有一种方案,能够根据文件夹里的文件去匹配从而动态引入组件。不仅仅适用vue文件也适用js文件

import { ref, computed, reactive, onMounted, watch, markRaw, defineAsyncComponent } from 'vue';

image.png

const modules = import.meta.glob('./components/*.vue');

image.png

 const link: any = modules[`./components/${routeAddress.value}.vue`]
            try {
                layouts.value = markRaw(defineAsyncComponent(link))
            } catch {
                console.log('路由不规范啊')
            }

image.png

image.png