Beginner LevelVue JS
How do you access DOM elements directly in Vue 3 using template refs?
❓ Interview Prompt: Explain template refs (ref="name"), accessing underlying HTML element instances, and onMounted lifecycle timing.
While Vue encourages declarative data-driven UI, accessing raw DOM elements is sometimes necessary for focusing inputs, triggering media playback, or initializing 3rd-party JS libraries.
Template Ref Rules:
1
Declare a 'ref(null)' variable in '<script setup>' with a name matching the 'ref="name"' HTML tag attribute.
2
In TypeScript, type the ref: 'ref<HTMLInputElement | null>(null)'.
3
The DOM element is 'null' during setup and becomes populated only after 'onMounted()'!
Code Implementation Example
html
<script setup lang="ts">
import { ref, onMounted } from 'vue';
// 1. Declare template ref initialized to null
const searchInput = ref<HTMLInputElement | null>(null);
onMounted(() => {
// 2. Access raw DOM node after mounting
searchInput.value?.focus();
});
</script>
<template>
<!-- 3. Bind ref attribute matching variable name -->
<input ref="searchInput" type="text" placeholder="Search..." />
</template>💡Focusing input DOM node directly using template refs in onMounted.
🎯 Interview Key Takeaway
Declare a ref matching the template ref="name" attribute. Access the underlying DOM node inside onMounted().
#Template Refs#DOM Access#Beginner
Back to all Vue JS Questions→