10、vue3注册全局组件

2023-02-21  本文已影响0人  蜗牛的学习方法

在项目里面components里面新建了一个Empty/index.vue组件,内容如下

// src/components/Empty/index.vue
<template>
  <div>这是一个全局组件</div>
</template>

1、全局注册使用第一种方式

在main.ts引入

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import Empty from './components/Empty/index.vue'

const app=createApp(App)

app.component('Empty',Empty)
app.mount('#app')

2、全局引入第二种方式

这种方式可以把多个组件的注册放在一起,避免都放在main.ts里面引起观感不好。
src/components/index.ts里面直接导出使用

// src/components/index.ts
import Empty from './Empty/index.vue'

export const useGlobalComponent = (app: any) => {
  app.component('Empty', Empty)
}

//main.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {useGlobalComponent} from './components/index'

const app=createApp(App)

useGlobalComponent(app)
app.mount('#app')

3、全局引入第三种方式

写法一

这种是根据components下面的文件夹名字来自动生成组件注册

// src/components/index.ts
const components:any= import.meta.globEager('./*/index.vue')
//提示被废弃就用下面这个
// const components:any= import.meta.glob('./*/index.vue',{eager:true})

export const useGlobalComponent = (app: any) => {
  const componentsData = Object.keys(components).map(key => {
    const template = components[key].default
    const nameData = key.split('/')
    return {name: nameData.length ? nameData[1] : null, template}
  })
  componentsData.forEach((item:any) => {
    if(item.name){
      app.component(item.name, item.template)
    }else{
      console.error("component registered failed", item)
    }
  })
}
//main.ts同上面的用法
...

写法二

// src/components/index.ts
const components:any= import.meta.globEager('./*/index.vue')
//提示被废弃就用下面这个
// const components:any= import.meta.glob('./*/index.vue',{eager:true})

export default {
  install: (app: any) => {
    const componentsData = Object.keys(components).map(key => {
      const template = components[key].default
      const nameData = key.split('/')
      return {name: nameData.length ? nameData[1] : null, template}
    })
    componentsData.forEach((item:any) => {
      if(item.name){
        app.component(item.name, item.template)
      }else{
        console.error("component registered failed", item)
      }
    })
  }
}

// main.ts
import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import './style.css'
import App from './App.vue'
import useGlobalComponent from './components/index' //看这

const app=createApp(App)
app.use(useGlobalComponent)  //看这 要用use就要用install,注册调用(app.use,会调用上面的install,并传参数)
app.mount('#app')
上一篇 下一篇

猜你喜欢

热点阅读