Vue.js Developer interview question · Most asked
What are template refs, and why do you need nextTick?
Summary
A template ref gives direct access to a DOM element or child component instance (ref="input" plus const input = ref(null), or useTemplateRef('input') in 3.5+), available after mount. nextTick() waits until Vue has applied pending reactive updates to the DOM, because Vue batches updates asynchronously.
Longer Answer
show.value = true; // the element is not in the DOM yet
await nextTick(); // DOM updated
input.value.focus();
Use template refs for focus management, measuring elements, and integrating non-Vue libraries (charts, maps). Prefer declarative state over manipulating the DOM directly.
Key Points
- Refs to DOM nodes or component instances.
- Available after mount.
- Updates are batched; nextTick waits for the DOM.
- useTemplateRef in 3.5+.
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- How do props work, and what is one-way data flow?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- Why does v-for need a key, and why should it not be the index?
- What are composables, and why did they replace mixins?