【问题标题】:How to add type support for global components in Vue 3?如何在 Vue 3 中添加对全局组件的类型支持?
【发布时间】:2021-12-07 05:18:31
【问题描述】:

所以我有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>

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

【问题讨论】:

    标签: typescript vue.js vuejs3


    【解决方案1】:

    vue 包导出一个GlobalComponents 接口,该接口可以是augmented 与您的全局组件定义。例如,您可以在src/global-components.d.ts 中添加模块扩充:

    // src/global-components.d.ts
    import Component1 from '@/components/Component1.vue'
    
    declare module 'vue' {
      export interface GlobalComponents {
        Component1: typeof Component1,
      }
    }
    

    【讨论】:

      【解决方案2】:

      我发现@tony19 的回答几乎是正确的——Volar 识别出该组件,但没有提供正确的类型提示。反而发现我需要扩展@vue/runtime-core

      // src/global-components.d.ts
      import Component1 from '@/components/Component1.vue'
      
      declare module '@vue/runtime-core' {
        export interface GlobalComponents {
          Component1: typeof Component1,
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-10
        • 2021-01-04
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-04
        • 2020-04-06
        • 2020-11-05
        相关资源
        最近更新 更多