- 舊寫法
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>