Skip to content

Vue3-Vite批量注册全局组件

  • 项目目录如下所示

项目文件结构图

  • 在公共全局组件目录下建立入口文件,添加方法
 export default function registerComponent(app){
 const modules = import.meta.globEager('./*.vue')
 for (const path in modules){
   const componentName = changeStr(
     path.replace(/^\.\//, '').replace(/\.\w+$/, '')
   )
   const config = modules[path].default || config
   app.component(componentName, config)
 }
}

function changeStr(str){
 return str.charAt(0).toUpperCase() + str.slice(1);
}
  • 在main.js中引入公用全局组件注册方法
  import { createApp } from 'vue'
  import App from './App.vue'
  import global from '@/components/common'
  const app = createApp(App)
  global(app)
  app.mount('#app')

测试结果如下: 导入组件结果图

Released under the MIT License.