前提
vue3 setup语法糖需要把某一模块的组件批量注册到当前模块的主文件中,第一想法是用全局挂载的方式,但是这些组件重复在全局上使用率几乎为零,也不想书写多个import *** from '***' ,下面分别说一下全局挂载和局部批量挂载组件
1,全局挂载组件
创建批量导入的工具文件
import type { App } from 'vue'
export default {
install(app: App) {
const components = import.meta.glob('./*.vue', { eager: true })
Object.values({ ...components }).forEach((module: any) => {
const component = module.default
const componentName = component.__file
.replace(/^.+\/([^/]+)\.vue$/, '$1') // 获取文件名
.replace(/^([A-Z])/, (m: any, p1: any) => p1.toLowerCase()) // 首字母小写
app.component(componentName, component)
})
},
}
在组件文件夹根目录中创建,只需要使用 import.meta.glob('./*.vue', { eager: true })把文件夹里的组件批量导入
在main.ts中进行全局挂载
import globalComponents from '@/pages/video-core/layouts'
app.use(globalComponents)
附文件夹层级图片:
2,局部挂载组件
前面说到 局部挂载可以使用 批量 import *** from '***' 进行注册,这里简单对批量import导入组件进行优化 ,在需要引入的文件中
<script lang="ts">
import { defineComponent } from 'vue'
const resolvedComponents = {} as any
//方式1 使用resolveComponent
const components = import.meta.glob('./layouts/*.vue', { eager: true })
Object.values({ ...components }).forEach((module: any) => {
const component = module.default
const componentName = component.__file
.replace(/^.+\/([^/]+)\.vue$/, '$1') // 获取文件名
.replace(/^([A-Z])/, (m: any, p1: any) => p1.toLowerCase()) // 首字母小写
resolvedComponents[componentName] = resolveComponent(component)
})
// 方式2 使用defineAsyncComponent
// const components = import.meta.glob('./layouts/*.vue')
// for (const path in components) {
// const componentName = path
// .replace(/^.+\/([^/]+)\.vue$/, '$1') // 获取文件名
// .replace(/^([A-Z])/, (m, p1) => p1.toLowerCase()) // 首字母小写
// const component = components[path] as any
// resolvedComponents[componentName] = defineAsyncComponent(component)
// }
export default defineComponent({
components: { ...resolvedComponents },
})
</script>