4. Vue3中使用TypeScript

直接參考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)需要用 \color{red}{defineComponent()} 來包裝組件。有了它,Vue 才可以通過 props 以及一些額外的選項(xiàng),比如 required: true 和 default 來推導(dǎo)出 props 的類型:
\color{red}{(這和沒學(xué)TS之前的寫法是一樣的)}

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)使用 \color{red}{PropType} 這個(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 }) {}
})
2.為組件的 emits 標(biāo)注類型
3.為計(jì)算屬性標(biāo)記類型
4.為事件處理函數(shù)標(biāo)注類型
5.擴(kuò)展全局屬性
6.擴(kuò)展自定義選項(xiàng)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容