為Vue3?組件標(biāo)注?TS?類型實(shí)例詳解
為 props 標(biāo)注類型
要說今年最熱門的前端技術(shù),Vue3 和 TS 絕對榜上有名了。據(jù)了解,已經(jīng)有很多公司在使用 Vue3 + TS + Vite 開發(fā)新項(xiàng)目了。那么我們也不能落后,今天就給大家分享一下如何在 Vue3 組件中結(jié)合 Composition-Api 使用 TS 類型。如果有不會(huì)或者不熟的小伙伴,一起學(xué)起來吧!
使用 <script setup>
當(dāng)使用 <script setup> 時(shí),defineProps() 宏函數(shù)支持從它的參數(shù)中推導(dǎo)類型:
<script setup lang="ts"> const props = defineProps({ foo: { type: String, required: true }, bar: Number }) props.foo // string props.bar // number | undefined </script>
這被稱為 運(yùn)行時(shí)聲明 ,因?yàn)閭鬟f給 defineProps() 的參數(shù)會(huì)作為運(yùn)行時(shí)的 props 選項(xiàng)使用。
第二種方式,通過泛型參數(shù)來定義 props 的類型,這種方式更加直接:
<script setup lang="ts"> const props = defineProps<{ foo: string bar?: number }>() </script>
這被稱為 基于類型的聲明 ,編譯器會(huì)盡可能地嘗試根據(jù)類型參數(shù)推導(dǎo)出等價(jià)的運(yùn)行時(shí)選項(xiàng)。
我們也可以將 props 的類型移入一個(gè)單獨(dú)的接口中:
<script setup lang="ts"> interface Props { foo: string bar?: number } const props = defineProps<Props>() </script>
基于類型的方式更加簡潔,但失去了定義 props 默認(rèn)值的能力。我們可以通過目前實(shí)驗(yàn)性的 響應(yīng)性語法糖 來解決:
<script setup lang="ts"> interface Props { foo: string bar?: number } // 響應(yīng)性語法糖 默認(rèn)值會(huì)被編譯為等價(jià)的運(yùn)行時(shí)選項(xiàng) const { foo, bar = 100 } = defineProps<Props>() </script>
這個(gè)行為目前需要在配置中顯式地選擇開啟:
// vite.config.js export default { plugins: [ vue({ reactivityTransform: true }) ] } // vue.config.js module.exports = { chainWebpack: (config) => { config.module .rule('vue') .use('vue-loader') .tap((options) => { return { ...options, reactivityTransform: true } }) } }
非 <script setup>
如果沒有使用 <script setup>,那么為了開啟 props 的類型推導(dǎo),必須使用 defineComponent()。傳入 setup() 的 props 對象類型是從 props 選項(xiàng)中推導(dǎo)而來。
import { defineComponent } from 'vue' export default defineComponent({ props: { message: String }, setup(props) { props.message // <-- 類型:string } })
為 emits 標(biāo)注類型
使用 <script setup>
在 <script setup> 中,emit 函數(shù)的類型標(biāo)注也可以使用 運(yùn)行時(shí)聲明 或者 基于類型的聲明 :
<script setup lang="ts"> // 運(yùn)行時(shí) const emit = defineEmits(['change', 'update']) // 基于類型 const emit = defineEmits<{ (e: 'change', id: number): void (e: 'update', value: string): void }>() </script>
我們可以看到,基于類型的聲明 可以使我們對所觸發(fā)事件的類型進(jìn)行更細(xì)粒度的控制。
非 <script setup>
若沒有使用 <script setup>,defineComponent() 也可以根據(jù) emits 選項(xiàng)推導(dǎo)暴露在 setup 上下文中的 emit 函數(shù)的類型:
import { defineComponent } from 'vue' export default defineComponent({ emits: ['change'], setup(props, { emit }) { emit('change') // <-- 類型檢查 / 自動(dòng)補(bǔ)全 } })
為 ref() 標(biāo)注類型
默認(rèn)推導(dǎo)類型
ref 會(huì)根據(jù)初始化時(shí)的值自動(dòng)推導(dǎo)其類型:
import { ref } from 'vue' // 推導(dǎo)出的類型:Ref<number> const year = ref(2020) // => TS Error: Type 'string' is not assignable to type 'number'. year.value = '2020'
通過接口指定類型
有時(shí)我們可能想為 ref 內(nèi)的值指定一個(gè)更復(fù)雜的類型,可以通過使用 Ref 這個(gè)接口:
import { ref } from 'vue' import type { Ref } from 'vue' const year: Ref<string | number> = ref('2020') year.value = 2020 // 成功!
通過泛型指定類型
或者,在調(diào)用 ref() 時(shí)傳入一個(gè)泛型參數(shù),來覆蓋默認(rèn)的推導(dǎo)行為:
// 得到的類型:Ref<string | number> const year = ref<string | number>('2020') year.value = 2020 // 成功!
如果你指定了一個(gè)泛型參數(shù)但沒有給出初始值,那么最后得到的就將是一個(gè)包含 undefined 的聯(lián)合類型:
// 推導(dǎo)得到的類型:Ref<number | undefined> const n = ref<number>()
為 reactive() 標(biāo)注類型
默認(rèn)推導(dǎo)類型
reactive() 也會(huì)隱式地從它的參數(shù)中推導(dǎo)類型:
import { reactive } from 'vue' // 推導(dǎo)得到的類型:{ title: string } const book = reactive({ title: 'Vue 3 指引' })
通過接口指定類型
要顯式地指定一個(gè) reactive 變量的類型,我們可以使用接口:
import { reactive } from 'vue' interface Book { title: string year?: number } const book: Book = reactive({ title: 'Vue 3 指引' })
為 computed() 標(biāo)注類型
默認(rèn)推導(dǎo)類型
computed() 會(huì)自動(dòng)從其計(jì)算函數(shù)的返回值上推導(dǎo)出類型:
import { ref, computed } from 'vue' const count = ref(0) // 推導(dǎo)得到的類型:ComputedRef<number> const double = computed(() => count.value * 2) // => TS Error: Property 'split' does not exist on type 'number' const result = double.value.split('')
通過泛型指定類型
你還可以通過泛型參數(shù)顯式指定類型:
const double = computed<number>(() => { // 若返回值不是 number 類型則會(huì)報(bào)錯(cuò) })
為事件處理函數(shù)標(biāo)注類型
在處理原生 DOM 事件時(shí),應(yīng)該給事件處理函數(shù)的參數(shù)正確地標(biāo)注類型。讓我們看一下這個(gè)例子:
<script setup lang="ts"> function handleChange(event) { // `event` 隱式地標(biāo)注為 `any` 類型 console.log(event.target.value) } </script> <template> <input type="text" @change="handleChange" /> </template>
沒有類型標(biāo)注時(shí),這個(gè) event 參數(shù)會(huì)隱式地標(biāo)注為 any 類型。這也會(huì)在 tsconfig.json 中配置了 "strict": true 或 "noImplicitAny": true 時(shí)報(bào)出一個(gè) TS 錯(cuò)誤。因此,建議顯式地為事件處理函數(shù)的參數(shù)標(biāo)注類型。此外,你可能需要顯式地強(qiáng)制轉(zhuǎn)換 event 上的屬性:
function handleChange(event: Event) { console.log((event.target as HTMLInputElement).value) }
為 provide / inject 標(biāo)注類型
provide 和 inject 通常會(huì)在不同的組件中運(yùn)行。要正確地為注入的值標(biāo)記類型,Vue 提供了一個(gè) InjectionKey 接口,它是一個(gè)繼承自 Symbol 的泛型類型,可以用來在提供者和消費(fèi)者之間同步注入值的類型:
import { provide, inject } from 'vue' import type { InjectionKey } from 'vue' const key = Symbol() as InjectionKey<string> provide(key, 'foo') // 若提供的是非字符串值會(huì)導(dǎo)致錯(cuò)誤 const foo = inject(key) // foo 的類型:string | undefined
建議將注入 key 的類型放在一個(gè)單獨(dú)的文件中,這樣它就可以被多個(gè)組件導(dǎo)入。
當(dāng)使用字符串注入 key 時(shí),注入值的類型是 unknown,需要通過泛型參數(shù)顯式聲明:
const foo = inject<string>('key') // 類型:string | undefined
注意注入的值仍然可以是 undefined,因?yàn)闊o法保證提供者一定會(huì)在運(yùn)行時(shí) provide 這個(gè)值。當(dāng)提供了一個(gè)默認(rèn)值后,這個(gè) undefined 類型就可以被移除:
const foo = inject<string>('foo', 'bar') // 類型:string
如果你確定該值將始終被提供,則還可以強(qiáng)制轉(zhuǎn)換該值:
const foo = inject('foo') as string
為 dom 模板引用標(biāo)注類型
模板 ref 需要通過一個(gè)顯式指定的泛型參數(shù)和一個(gè)初始值 null 來創(chuàng)建:
<script setup lang="ts"> import { ref, onMounted } from 'vue' const el = ref<HTMLInputElement | null>(null) onMounted(() => { el.value?.focus() }) </script> <template> <input ref="el" /> </template>
注意為了嚴(yán)格的類型安全,有必要在訪問 el.value 時(shí)使用可選鏈或類型守衛(wèi)。這是因?yàn)橹钡浇M件被掛載前,這個(gè) ref 的值都是初始的 null,并且 v-if 將引用的元素卸載時(shí)也會(huì)被設(shè)置為 null。
為組件模板引用標(biāo)注類型
有時(shí),我們需要為一個(gè)子組件添加一個(gè)模板 ref,以便調(diào)用它公開的方法。比如,我們有一個(gè) MyModal 子組件,它有一個(gè)打開模態(tài)框的方法:
<!-- MyModal.vue --> <script setup lang="ts"> import { ref } from 'vue' const isContentShown = ref(false) const open = () => (isContentShown.value = true) defineExpose({ open }) </script>
為了獲取 MyModal 的類型,我們首先需要通過 typeof 得到其類型,再使用 TypeScript 內(nèi)置的 InstanceType 工具類型來獲取其實(shí)例類型:
<!-- App.vue --> <script setup lang="ts"> import MyModal from './MyModal.vue' const modal = ref<InstanceType<typeof MyModal> | null>(null) const openModal = () => { modal.value?.open() } </script>
Ok,以上就是在 Vue3 組件中使用 TS 類型的基本方法,也是我最近的 Vue3 學(xué)習(xí)筆記。歡迎在評論區(qū)交流討論,一起學(xué)習(xí)成長。
如果對你有所幫助,不要忘了點(diǎn)贊支持一下哦!????
參考文檔:
staging-cn.vuejs.org/guide/intro…
以上就是為Vue3 組件標(biāo)注 TS 類型實(shí)例詳解的詳細(xì)內(nèi)容,更多關(guān)于Vue3 組件標(biāo)注 TS 類型的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
iview tabs 頂部導(dǎo)航欄和模塊切換欄的示例代碼
這篇文章主要介紹了iview tabs 頂部導(dǎo)航欄和模塊切換欄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03vue-echarts如何實(shí)現(xiàn)圖表組件封裝詳解
由于在項(xiàng)目中需要對數(shù)據(jù)進(jìn)行可視化處理,也就是用圖表展示,所以下面這篇文章主要給大家介紹了關(guān)于vue-echarts如何實(shí)現(xiàn)圖表組件封裝的相關(guān)資料,需要的朋友可以參考下2022-05-05vue中watch和computed為什么能監(jiān)聽到數(shù)據(jù)的改變以及不同之處
這篇文章主要介紹了vue中watch和computed為什么能監(jiān)聽到數(shù)據(jù)的改變以及不同之處,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12Vue3中使用defineCustomElement 定義組件詳解
這篇文章主要為大家介紹了Vue3中使用defineCustomElement 定義組件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10