好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Vue3中注册全局的组件,并在TS中添加全局组件提示方式

Vue3中注册全局的组件

1. 在 src/components 中新建 index.ts 用来将所有需要全局注册的组件导入

?: 如果使用的是 JS 可以删除类型校验

import type { Component } from 'vue'
import SvgIcon from './SvgIcon/index.vue'

// ?如果使用的是 JS 可以删除类型校验
const components: {
  [propName: string]: Component
} = {
  SvgIcon
}
export default components

2. 在 main.ts 中导入

?这里使用循环的方式, 将每个全局组件进行注册

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).mount('#app')

// 注册全局的组件
for (const componentItme in globalComponent) {
  app测试数据ponent(componentItme, globalComponent[componentItme])
}

3. 如果使用 TS 编写,还需要在和 main.ts 同级的目录, 创建一个 components.d.ts , 用来处理组件引入报错的问题和添加组件提示

import SvgIcon from '@/components/SvgIcon/index.vue'
declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    SvgIcon: typeof SvgIcon
  }
}

4. 最后直接导入即可

Vue3踩坑--全局注册组件

我的框架:vue3+vite+ts+naiveUI

步骤一:

创建一个loading文件夹

index.vue

index.ts

//loading/index.vue
<script lang="ts">
import { NSpace, NSpin } from 'naive-ui'
import { defineComponent } from 'vue'
export default defineComponent({
? name: 'HsNavLoading',
? components: {
? ? NSpace,
? ? NSpin
? }
})

//loading/index.ts
import { App } from 'vue'
import loading from './index.vue'

export default {
? install(app: App) {
? ? app测试数据ponent(loading.name, loading)
? }
}

步骤二:

components文件夹下创建index.ts一次引入多个全局组件并导出

//components/index.ts
import { App } from 'vue'
import loading from '@/components/Loading/index'

const components = [loading]
export default {
? install(app: App) {
? ? components.map((item) => {
? ? ? app.use(item)
? ? })
? }
}

步骤三:

main.js引入

//main.js
import { createApp } from 'vue'
import App from './App.vue'
import components from '@/components/index'
const app = createApp(App)
app.use(router).mount('#app')
app.use(components)

步骤四:

在单页面中使用

<hsNavLoading :show="isLoading" />

遇到的坑:

一开始loading/index.vue使用setup语法糖,通过 defineExpose 来导出name

报错

Failed to resolve component: hsNavLoading If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.

<script lang="ts" setup>
import { NSpace, NSpin } from 'naive-ui'
defineExpose({
? ?name: 'HsNavLoading'
})

</script>

解决办法:如步骤一,把语法糖换掉

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

查看更多关于Vue3中注册全局的组件,并在TS中添加全局组件提示方式的详细内容...

  阅读:32次