例如组件使用频率非常高,几乎每个页面都在使用便可以封装成全局组件
1.注册单个全局组件
在main.ts 引入我们的组件跟随在createApp(App) 后面 切记不能放到mount 后面这是一个链式调用用
其次调用 component 第一个参数组件名称 第二个参数组件实例
import { createApp } from 'vue'
import App from './App.vue'
import './assets/css/reset/index.less'
import Card from './components/Card/index.vue'
createApp(App).component('Card',Card).mount('#app')
//.component('Card',Card)就是注册全局组件 (‘自定义键名’,组件名)
使用方法
直接在其他vue页面 立即使用即可 无需引入
<template>
<Card></Card>
</template>
2.批量注册全局组件
遇到要注册很多个全局组件时,可以定义中间件,让中间件去完成组件注册,然后main.js再引入使用这个中间件
在src/components
中新建index.ts
用来将所有需要全局注册的组件导入
✨: 如果使用的是 JS
可以删除类型校验
1 2 3 4 5 6 7 8 9 10 | import type { Component } from 'vue' // import type 是用来协助进行类型检查和声明的,在运行时是完全不存在的。 import SvgIcon from './SvgIcon/index.vue' // ✨如果使用的是 JS 可以删除类型校验 const components: { [propName: string]: Component //字面量类型,每个属性值类型为组件的类型 } = { SvgIcon } export default components |
2. 在main.ts
中导入
✨这里使用循环的方式, 将每个全局组件进行注册
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' // 基于断点的隐藏类 Element 额外提供了一系列类名,用于在某些条件下隐藏元素 import App from './App.vue' import router from './router' import { store, key } from './store' import globalComponent from '@/components/index' //引入需要注册的全部组件 const app = createApp(App) app.use(store, key).use(router).use(ElementPlus) // 注册全局的组件 (对所有需要注册的组件进行遍历并注册) for (const componentItme in globalComponent) { app.component(componentItme, globalComponent[componentItme]) } app.mount( '#app' ) //需要注册完组件后才挂载 |
3. 如果使用TS
编写,还需要在和main.ts
同级的目录, 创建一个components.d.ts
, 用来处理组件引入报错的问题和添加组件类型提示
1 2 3 4 5 6 | import SvgIcon from '@/components/SvgIcon/index.vue' //要扩充@vue/runtime-core包的声明 declare module '@vue/runtime-core' { export interface GlobalComponents { //这里扩充"ComponentCustomProperties"接口 SvgIcon: typeof SvgIcon } } |
4. 最后直接导入即可