Question presented to candidate:
"You need to focus an input when a page opens, measure a chart container for a third-party library, and call reset() on a child form component. How do you get hold of the DOM element and the child component in Vue 3, and when are they actually available?"
What a strong answer should cover:
- Template refs: put
ref="name"on an element or component; in<script setup>read it through a matchingref(null)or, since Vue 3.5,useTemplateRef("name"); in the Options API throughthis.$refs.name. - Timing: the ref is
nullduringsetupand the first render, filled beforeonMountedruns, and set back tonullwhen the element unmounts (for example behindv-if), with the DOM change applied afternextTick. - On a component, the ref holds the child's public instance, not a DOM node: a
<script setup>child shows only what it lists indefineExpose, plus built-ins such as$el. v-forrefs collect an array (order not guaranteed to match the source), and function refs (:ref="el => ...") give full control but are called on every update.- Prefer declarative tools first; use refs for focus, measurement, scrolling, media and third-party libraries.
$elon a multi-root component is a placeholder text node, so expose a method or ref the real element instead.
Clarifying questions expected:
- "Is the element always rendered, or is it behind a
v-ifor av-for?" - "Is the child component a
<script setup>component, and does it exposereset?"
Code / implementation expected: Yes β an element ref used in onMounted, and a component ref calling an exposed method.