- 旧写法
ref的字符串需要跟js中ref定义的变量名称一样
类型丢失,无法获取到ref定义的title类型
<template>
<div>
<h1 ref="title">Hello Vue3.5</h1>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const title = ref(null)
// const title = ref<HTMLElement | null>(null) // 可以通过以下方式标注类型,但是不完全
onMounted(() => {
console.log(title.value)
})
</script>
- 新写法
<template>
<div>
<h1 ref="title">Hello Vue3.5</h1>
</div>
</template>
<script setup>
import { useTemplateRef } from 'vue'
const h1 = useTemplateRef('title')
onMounted(() => {
console.log(h1.value)
})
</script>