Template ref cho phép truy cập DOM element hoặc component instance trực tiếp:
vue
<script setup>
import { ref, onMounted } from 'vue'
// Ref cho DOM element
const inputEl = ref<HTMLInputElement | null>(null)
// Ref cho component instance
const modalRef = ref<InstanceType<typeof Modal> | null>(null)
onMounted(() => {
inputEl.value?.focus() // Auto-focus khi mount
})
function openModal() {
modalRef.value?.open() // Gọi method của child component
}
</script>
<template>
<input ref="inputEl" type="text" />
<Modal ref="modalRef" />
</template>Pitfall: ref.value là null trước khi component mount — luôn kiểm tra trong onMounted hoặc dùng optional chaining ref.value?.method().