Vite自动化注册全局组件

注册组件

import { Component } from 'vue'
 
interface FileType {
  [key: string]: Component
}
interface componentItem {
  name: string
  sfc: Component
}
 
/*
 * 从common、layouts、graph文件夹导入所有的组件
 * 每一个文件需要是独立文件夹,通过index.vue导出组件
 * “组件名必须写!!!”,将自动组件名注册
 */
 
const commonFiles: Record = import.meta.globEager(
  '/src/components/common/*/index.vue'
)
const layoutFiles: Record = import.meta.globEager(
  '/src/components/layouts/*/index.vue'
)
const graphFiles: Record = import.meta.globEager(
  '/src/components/graph/*/index.vue'
)
 
const componentList: componentItem[] = []
const files: Record = Object.assign(commonFiles, layoutFiles, graphFiles)
 
Object.keys(files).forEach((c: string) => {
  const component = files[c]?.default
  componentList.push({ name: component.name as string, sfc: component })
})
 
export default componentList

main.js

import { App } from 'vue'

import commonComponents from './common-auto-import-components'

import echartsComponents from './echarts-components'

import elementComponents from './element-plus-components'

const customComponents = [
  // 便于自动注册每一个自定义组件
  ...echartsComponents,
  ...commonComponents
]

export default function installComponents(app: App) {
  // 按需注册elementPlus的组件
  elementComponents.forEach((component) => {
    app.use(component)
  })
  // 注册自定义组件
  customComponents.forEach((component) => {
    app.component(component.name, component.sfc)
  })
}

你可能感兴趣的:(Vite自动化注册全局组件)