看吧: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> } })