vue3标签模板上的ref类型注解

子组件
<script setup lang="ts">
import { ref, defineExpose } from 'vue';
const num = ref<number>(10)
defineExpose({
  num,//把值暴露出去,父级可以通过ref获取 
})
</script>

<template>
  <h1>我是组件</h1>

</template>

<style scoped></style>
父组件
<template>
   <ul>
    <input type="text" ref="iptRef">
    <a href="" ref="aRef"></a>
    <helloworld ref="refChild"></helloworld>
  </ul>
</template>

 

可以看我声明两个标签的ref,还有一个自定义组件的ref模板

我想通过ref来获取这个标签

可以通过

const iptRef = ref<HTMLInputElement | null>(null) //来获取 HTMLInputElement 是这个标签的类型,null是防止这个类型没有渲染完成
const aRef = ref<HTMLAnchorElement | null>(null)

//自定义组件 可以通过
InstanceType<typeof 组件名> 来获取组件名
const refChild = ref<InstanceType<typeof helloworld> | null>(null)
onMounted(() => {
iptRef.value
?.focus() //可能 为null所以要加? console.log(aRef.value?.href);

 console.log(refChild.value?.num);
})

 

posted @ 2024-06-19 20:37  light丶  阅读(84)  评论(0)    收藏  举报