直接參考Vue官方文檔。
https://cn.vuejs.org/guide/typescript/overview.html#overview
一、TS與組合式API
1.為組件的 props 標(biāo)注類型
2.為組件的 emits 標(biāo)注類型
3.為 ref() 標(biāo)注類型
4.為 reactive() 標(biāo)注類型
5.為 computed() 標(biāo)注類型
6.為事件處理函數(shù)標(biāo)注類型
7.為 provide / inject 標(biāo)注類型
8.為模板引用標(biāo)注類型
9.為組件模板引用標(biāo)注類型
二、TS與選項(xiàng)式AIP
1.為組件的 props 標(biāo)注類型
(1)選項(xiàng)式 API 中對(duì) props 的類型推導(dǎo)需要用 來包裝組件。有了它,Vue 才可以通過 props 以及一些額外的選項(xiàng),比如 required: true 和 default 來推導(dǎo)出 props 的類型:
import { defineComponent } from 'vue'
export default defineComponent({
// 啟用了類型推導(dǎo)
props: {
name: String,
id: [Number, String],
msg: { type: Array, required: true, default: ()=>[] },
},
setup(props, { slots, attrs, expose, emit }) {}
}
(2)使用 這個(gè)工具類型來標(biāo)記更復(fù)雜的 props 類型,如 多層級(jí)對(duì)象 或 函數(shù)簽名:
import { defineComponent } from 'vue'
import type { PropType } from 'vue'
interface Book {
title: string
author: string
year: number
}
export default defineComponent({
props: {
book: {
// 提供相對(duì) `Object` 更確定的類型
type: Object as PropType<Book>,
required: true
},
// 也可以標(biāo)記函數(shù)
callback: Function as PropType<(id: number) => void>
},
setup(props, { slots, attrs, expose, emit }) {}
})