Trung BìnhVue.js iconVue.js

Template refs — cách truy cập DOM element và child component trong Vue 3?

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.valuenull trước khi component mount — luôn kiểm tra trong onMounted hoặc dùng optional chaining ref.value?.method().

Xem toàn bộ Vue.js cùng filter theo level & chủ đề con.

Mở danh sách Vue.js