主要解决公用组件使用时,多次引入的不必要性,一次引入,自后便不用担心引入的问题了,只需要按需取好对应组件的名字。
下述代码具体写的位置可根据自己心意去写,但是获取组件文件的路径要配置正确。
javascript
import { defineAsyncComponent } from 'vue'
export default function registerGlobalComponents(app) {
const components = import.meta.glob('./components/**/*.vue', { eager: true })
for (const path in components) {
const componentName = path
.split('/')
.pop()
.replace(/\.\w+$/, '')
app.component(componentName, defineAsyncComponent(components[path].default))
}
}
- main.js
javascript
import { createApp } from 'vue'
import App from './App.vue'
import registerGlobalComponents from './components/index.js';
const app = createApp(App)
registerGlobalComponents(app)
app.mount('#app')
2026-03-10