vite3构建的项目中自动注册vue3单文件组件

问题

vue2官网文档中专门介绍如何基础组件的自动化全局注册,这样可以直接使用自定义组件而不用写一堆import,但是vue3的官网文档中却没有提到,只有全局注册

解决

利用vite3特有的glob-import

自定义插件

  • 方案1 懒加载
    yarn build打包时每个vue都是独立的js
    plugins.ts
import { App, Component, defineAsyncComponent, AsyncComponentLoader } from 'vue'

export const componentsRegistration = {
  install: (app: App) => {
    const modules: Record<string, AsyncComponentLoader> = import.meta.glob('../components/**/*.vue')
    for (const path in modules) {
      const componentName = path
        .split('/')
        .pop()
        ?.replace(/\.\w+$/, '') as string
      const component = defineAsyncComponent(modules[path])
      app.component(componentName, component)
    }
  }
}
  • 方案2直接加载
    yarn build打包时合成一个js
    plugins.ts
import { App } from 'vue'

export interface ComponentModule {
  default: Component
}

export const componentsRegistration = {
  install: (app: App) => {
    const modules: Record<string, ComponentModule> = import.meta.glob('../components/**/*.vue', { eager: true })
    for (const path in modules) {
      let componentName = path
        .split('/')
        .pop()
        ?.replace(/\.\w+$/, '')
      componentName = componentName || ''
      const module = modules[path]
      app.component(componentName, module.default)
    }
  }
}

使用插件

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import { componentsRegistration} from './global/plugins'

const app = createApp(App)
app.use(componentsRegistration)
app.mount('#app')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值