看吧:https://cn.vuejs.org/guide/typescript/composition-api.html
为组件的 props 标注类型
<script setup lang="ts">
const props = defineProps({
  foo: { type: String, required: true },
  bar: Number
})
props.foo // string
props.bar // number | undefined
</script>

这被称之为“运行时声明”,因为传递给 defineProps() 的参数会作为运行时的 props 选项使用。
然而,通过泛型参数来定义 props 的类型通常更直接:

<script setup lang="ts">
const props = defineProps<{
  foo: string
  bar?: number
}>()
</script>

这被称之为“基于类型的声明”。我们也可以将 props 的类型移入一个单独的接口中:

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}
const props = defineProps<Props>()
</script>

组件传值示例:<MyComponent :foo="fooStr" :bar="barStr" @callback="search()"></MyComponent>
若要传入一个对象,则可以稍微改变一下:

<script setup lang="ts">
interface Props {
  foo: string
  bar?: number
}
const props = defineProps<{Info:Props}>();
</script>

组件传值示例:<MyComponent :Info="propsObj" @callback="search()"></MyComponent>
propsObj就是interface Props 类型的实例。

复杂的 prop 类型
通过基于类型的声明,一个 prop 可以像使用其他任何类型一样使用一个复杂类型:

<script setup lang="ts">
interface Book {
  title: string
  author: string
  year: number
}

const props = defineProps<{
  book: Book
}>()
</script>

对于运行时声明,我们可以使用 PropType 工具类型:

import type { PropType } from 'vue'

const props = defineProps({
  book: Object as PropType<Book>
})

其工作方式与直接指定 props 选项基本相同:

import { defineComponent } from 'vue'
import type { PropType } from 'vue'

export default defineComponent({
  props: {
    book: Object as PropType<Book>
  }
})

 

posted on 2024-04-10 17:33  邢帅杰  阅读(1)  评论(0编辑  收藏  举报