💚 Vue.js Beginner

What are Vue template refs?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Vue.js topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Template refs provide direct access to a DOM element or child component instance from the script. Useful for: focusing inputs programmatically, triggering animations, accessing third-party library instances, calling child component methods. Composition API: declare a ref with the same name as the template attribute: <script setup> import { ref, onMounted } from "vue"; const inputRef = ref(null); // null before mount onMounted(() => { inputRef.value.focus(); // DOM element available }); </script> <template><input ref="inputRef"></template>. Component ref: accessing a child component — gets the component's public interface (exposed properties via defineExpose): <ChildComponent ref="childRef">; childRef.value.publicMethod();. defineExpose(): by default, components using <script setup> are closed — their internal state isn't accessible via refs. Use defineExpose to selectively expose: defineExpose({ reset, focus });. Options API: this.$refs.inputRef.focus(). v-for with refs: <li v-for="item in items" :ref="el => { if (el) itemRefs[item.id] = el }"> — collect refs from list items. Important: template refs are only available after mounting — don't access in setup() directly, use onMounted().

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.