Vue3 + TS 如何給組件添加類型標(biāo)注

當(dāng)我們?cè)?Vue 項(xiàng)目里獲取組件的實(shí)例時(shí),一般都是在 <template> 模板直接 ref="your name",這種方式實(shí)際也是調(diào)用 document.getElementXXX ,但是在 TS 語(yǔ)言下有一個(gè)問(wèn)題,我們?cè)撊绾味x這個(gè)類型,一般情況下開(kāi)發(fā)工具無(wú)法正確提示該組件的方法,但是我們可以通過(guò)正確的類型標(biāo)注來(lái)輔助 TS 進(jìn)行類型推斷。

子組件 CheckBox.vue

<script setup lang="ts">
import cbChecked from '~/assets/images/cb-checked.png'
import cbUnchecked from '~/assets/images/cb-unchecked.png'
const props = withDefaults(
  defineProps<{
    isChecked?: boolean
  }>(),
  {
    isChecked: false,
  },
)
const emits = defineEmits(['update:isChecked'])
const localStatus = useVModel(props, 'isChecked', emits)
const println = (msg: string) => {
  console.log(`父組件調(diào)用 msg=${msg}`)
}
function printlnTest() {
  console.log('父組件調(diào)用 printlnTest')
}
defineExpose({
  printlnTest,
  println,
})
</script>

<template>
  <img
    class="w-0.48rem h-0.48rem"
    :aria-checked="localStatus"
    :src="localStatus ? cbChecked : cbUnchecked"
    alt="checkbox" @click="localStatus = !localStatus"
  >
</template>

父組件

import CheckBox from '@/xxx/components/CheckBox.vue'
import type CheckBoxType from '@/xxx/components/CheckBox.vue'
const checkbox = ref<InstanceType<typeof CheckBoxType> | null>()
<template>
  <CheckBox
   ref="checkbox"
   v-model:is-checked="introducePage.checkBoxStatus"
   />
</template>

這個(gè)時(shí)候,當(dāng)我們輸入checkbox.value?. 時(shí),編譯器就會(huì)自動(dòng)提示可以調(diào)用 defineExpose 公開(kāi)的函數(shù)了。


image.png

最后解釋一下代碼邏輯, typeof 是獲取該組件的類型,但是光靠這個(gè)關(guān)鍵字無(wú)法獲取到組件內(nèi)部的方法的,因?yàn)檫@是基于模板創(chuàng)建的類型而不是組件實(shí)例的類型,所以你得通過(guò) InstanceType 來(lái)獲取。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容