在utils文件夹下新建registGlobComp.ts
import { defineAsyncComponent } from 'vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// 注册 components 文件夹下的组件
export default function(app) {
const modules = import.meta.glob('../components/**/index.vue')
for (const [path, component] of Object.entries(modules)) {
app.component(path.slice(14, -10), defineAsyncComponent(component))
}
}
// 注册 icon 组件
export const registIconComponents = (app) => {
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
}
在main.ts中使用
import registGlobComp, { registIconComponents } from '@/utils/registGlobComp'
const app = createApp(App)
// 注册全局组件
registGlobComp(app)
registIconComponents(app)
// ...略
app.mount('#app')