【问题标题】:How to type vue instance out of `defineComponent()` in vue 3?如何在 vue 3 中从`defineComponent()` 中键入 vue 实例?
【发布时间】:2021-01-07 03:47:44
【问题描述】:

如您所知,从 Vue 3 开始,组件可以用 TypeScript 编写:

/// modal.vue

<template>
  <div class="modal"></div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Modal",
  props: {
    foo: String,
    bar: String
  },
  mounted() {
    this.$props.foo // how to type `this` out of this context?
  }
});
</script>

我的问题是如何从defineComponent 函数中输入 vue 实例?

/// another ts file.
let modal:???; // what the `???` should be?

modal.$props.foo // infer `$props.foo` correctly

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    我要给出的“简单”答案是使用ReturnType&lt;typeof defineComponent&gt;,但它不携带任何类型信息。当我开始研究如何将ReturnType 与泛型方法一起使用时,我跌倒了stackoverflow rabbit hole where these seemed like something to explore

    不过看了之后,vue 有一个导出的类型ComponentPublicInstance 可以相当容易地使用。 ComponentPublicInstance 也有一些不同的泛型参数。

    import { ComponentPublicInstance } from 'vue';
    
    let instance: ComponentPublicInstance<{ prop: string }, { value: string }>;
    

    【讨论】:

    • 非常适合组件,但对于没有 &lt;script&gt; 标记的组件(例如,仅具有 &lt;template&gt; 的组件)会引发类型错误。
    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2021-07-01
    • 2018-02-15
    • 1970-01-01
    • 2021-03-13
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多