【问题标题】:Vue3 typescript. How to get correct component type automaticallyVue3 打字稿。如何自动获取正确的组件类型
【发布时间】:2021-07-07 01:39:23
【问题描述】:

如果我有一个 Vue3 组件,HelloWorld 就像是

<template>
  <div class="hello">
   {{name}}
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  data() {
    return {
      name: 'hello'
    }
  },
  methods: {
    setName(name: string): void {
      this.name = name
    }
  }
})
</script>

如果我想使用这个组件

<template>
  <div>
    <hello-wrold ref="hello">
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import HelloWolrd from './hello-world'
export default defineComponent({
  mounted () {
    console.log(this.$refs.hello.name) // ?
    this.$refs.hello.setName('stackoverflow') // ?
  }
})
</script>

typescript 无法获得关于 HelloWorld 组件的正确类型,我应该给出什么样的类型? 这个我试过了,不行

  type Hello = typeof HelloWorld;
  (this.$refs.hello as Hello).name

或者这个,也不行

  type Hello = InstanceType<typeof HelloWorld>;
  (this.$refs.hello as Hello).name

  type Hello2 = ComponentPublicInstance<typeof HelloWorld>;
  (this.$refs.hello as Hello).name

如果我使用这种方式,它可以工作,但我认为这不是一个好主意,因为它不是自动的

  type Hello = ComponentPublicInstance<unknown, unknown, { name: string }, ComputedOptions, {setName: (name: string) => void}>
  (this.$refs.hello as Hello).name // can work

那么,我应该使用什么 vue3 API 或 ts API 来自动获取组件类型?

【问题讨论】:

    标签: typescript vuejs3


    【解决方案1】:

    我知道。。InstanceType。这是工作。 问题是 Vetur 扩展。

    【讨论】:

      猜你喜欢
      • 2021-05-12
      • 2021-02-10
      • 2022-12-10
      • 2022-01-19
      • 1970-01-01
      • 2021-02-17
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多