vue3使用ts定义组件的声明文件

1,344 阅读1分钟
定义一个组件 如Svg
<!--
 * @Description: svg组件 结合 vite-plugin-svg-icons使用
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2022-08-18 17:00:23
-->
<script setup lang="ts">
defineProps<{ name: string; className?: string }>()
</script>
<template>
  <svg class="svg-style" :class="className">
    <use :href="'#icon-' + name"></use>
  </svg>
</template>
<style lang="scss" scoped>
.svg-style {
  width: 100px;
  height: 100px;
}
</style>

在components文件夹下创建一个index.ts
import type { Component } from 'vue'
//引入所有组件
import Svg from './Svg/index.vue'
const components: { [prop: string]: Component } = {
  Svg
}
export default components
注册组件
书写自定义组件的声明文件
//在src目录下创建components.d.ts文件并写入
import Svg from '@/components/Svg/index.vue'
declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    Svg: typeof Svg
  }
}

此时在页面中使用组件就会有提示了!