目录
2、在auto文件夹下创建index.ts和其他需要注册的组件
提供一个思路,可根据自己的实际情况进行调整
1、首先在components文件夹下创建auto文件夹
- auto用于放置需要自动注册的组件

2、在auto文件夹下创建index.ts和其他需要注册的组件
- index.ts用于组件注册相关的索引逻辑
- 其他文件夹则为组件

3、index.ts写入组件注册索引逻辑
import {App, defineAsyncComponent } from 'vue'
// 默认一个文件夹文件自动注册全局组件
export default {
install(app: App) {
// import.meta.glob是vite的api
// import.meta.globEager新的vite版本已弃用
const components = import.meta.glob('./*/index.vue')
// 遍历组件模块实现自动注册
for (const [key, value] of Object.entries(components)) {
// 拼接组件注册的 name
const componentName = 'auto-' + key.replace('./', '').split('/')[0]
console.log(componentName);
// 通过 defineAsyncComponent 异步导入指定路径下的组件
app.component(componentName, defineAsyncComponent(value))
}
}
}
4、main.ts引入auto文件夹的index.ts文件
- 可根据自己的实际情况进行路由引入

5、demo文件夹index.vue配置我们的组件
- 组件识别取得是文件夹的名字,这里需要唯一

6、验证
组件名:componentName = 'auto-' + key.replace('./', '').split('/')[0]
'auto-':表示是自动识别,后面跟的是组件的文件夹名


文章描述了在Vue项目中自动注册组件的过程,包括在components下创建auto文件夹,编写index.ts文件进行组件注册,以及在main.ts引入并应用这些注册。组件名基于文件夹名字生成,确保唯一性。
607

被折叠的 条评论
为什么被折叠?



