Question presented to candidate:
"Vue 3.5 added useTemplateRef(). Before that we wrote const input = ref(null) and ref="input" in the template and it worked. What does useTemplateRef() actually fix, and would you migrate existing code to it?"
What a strong answer should cover:
useTemplateRef("key")returns a readonly shallow ref that Vue fills with the element or component whoserefattribute equals"key", matched by a runtime string, not by variable name.- The old pattern depended on the compiler matching a variable name to the attribute, which breaks for dynamic refs (
:ref="activeKey"): it works against the dev server but staysnullin a production build. - Because only a string is needed, a composable can own the template ref (
useAutofocus("search")), and keys need not be valid JavaScript identifiers. - With Vue language tools, the type is inferred from the template: an element ref is typed as that element, a component ref as its exposed instance.
- Behaviour details: it is
nulluntil mount, an array insidev-for, assigning to it is refused, and a seconduseTemplateRefwith the same key warns. - Migration: new code should use it; old static refs keep working, but dynamic string refs and refs created inside composables are worth migrating first.
Clarifying questions expected:
- "Are any of our refs dynamic, or created inside composables?"
- "Are we on Vue 3.5 and current Vue language tools?"
Code / implementation expected: Yes β useTemplateRef in a component, ideally inside a small composable, and an example of a dynamic ref key.