posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
看吧: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   邢帅杰  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2018-04-10 vs调试的时候出错:无法启动程序,操作在当前状态中是非法的
2017-04-10 sql添加/移除约束
点击右上角即可分享
微信分享提示