如何使用打字稿在 vue3 中手动定义道具类型

jok*_*lou 6 vue.js vuejs3

我可以

defineComponent({
  props: {
    name: { type: String as PropType<string> }
  }
})
Run Code Online (Sandbox Code Playgroud)

告诉 vue3 我的props类型是{ name: string },但是如果我有几个组件具有相同的 props 类型,我该如何共享定义?

如果我定义道具:

const props = {
  name: String as PropType<string>
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

defineComponent({
  props: props,
})
Run Code Online (Sandbox Code Playgroud)

不行,我在props的setup函数中得到的类型不对。

bra*_*bag -5

如果您在 Vue 2 中使用组合 API 来准备切换到 Vue 3,则必须使用PropType该包中的而不是该vue包。

// Wrong for Vue 2
import Vue, { PropType } from 'vue'
import { defineComponent } from '@vue/composition-api'

// Right for Vue 2
import { defineComponent, PropType } from '@vue/composition-api'
Run Code Online (Sandbox Code Playgroud)

  • 这不是问题,作者明确写的是“Vue3”而不是“Vue2” (2认同)