如何在 Vue 3 中添加对全局组件的类型支持?

2024-03-09

所以我有Component1,

<!-- Component1 -->
<script lang="ts" setup>
defineProps<{ msg: string }>()
</script>

<template>
  <p>{{ msg }}</p>
</template>

然后我在全球范围内注册它,

// main.ts
import { createApp } from "vue"
import App from "./App.vue"
import Component1 from "./Component1.vue"

const app = createApp(App)
app.component("Component1", Component1)
app.mount("#app")

之后我用它作为,

<script setup lang="ts"></script>

<template>
  <Component1 />
</template>

但是我没有得到 props 的类型推断Component1。那么如何为这个全局组件添加打字稿支持呢?


The vue包导出aGlobalComponents接口可以是增强的 https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation与您的全局组件的定义。例如,您可以在中添加模块增强src/global-components.d.ts, as 在 Volar 文档中看到 https://github.com/johnsoncodehk/volar/blame/1b90234ec6f10a3c0f080d0310711c2cd8de02dd/extensions/vscode-vue-language-features/README.md#L95-L100:

// src/global-components.d.ts
import Component1 from '@/components/Component1.vue'

declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    Component1: typeof Component1,
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Vue 3 中添加对全局组件的类型支持? 的相关文章

随机推荐