All jobs / Frontend / web developer / Vue
Frontend / web developer interview question · 0–1 years
In a Vue 3 component using script setup, you try to focus an input through a template ref at the top of setup and it is null. Why, and where does the code go?
The strongest answer
setup runs before the component is rendered, so the element does not exist yet. DOM access belongs in onMounted, when the template ref has been filled
Why it works
Exactly — setup is before render; onMounted is the first hook where the DOM and template refs exist.
What a good answer covers
- No DOM before mount.
- setup runs before render.
- Touch elements in onMounted.
- Clean up in onUnmounted.
Answers that fall short
- Close, but not the strongest: Use nextTick in setup and focus the input in its callback
Waiting is the right instinct, but the lifecycle hook states the intent and does not depend on timing. - Weak: Template refs only work in the Options API, so I would switch this component back
Template refs work in the Composition API: a ref with the matching name, or useTemplateRef in recent versions. - Red flag: Skip Vue for this and use document.querySelector with a timer until the input shows up
Polling the document bypasses the component model and breaks as soon as two instances are on the page.
Who gets asked this
More Vue questions
- In setup, a developer writes const { count } = state, where state is a reactive object. The template shows…
- In Vue, when do you use a computed property and when a watcher?
- A user page loads its data in onMounted. Clicking from /users/1 to /users/2 changes the URL, but the page…
- What is wrong with the composable, and what is the contract a composable should follow?
- How do you restructure state, and what rule do you give the team?
- A five-year-old Vue codebase is on Vue 3 but written entirely in the Options API with mixins and Vuex. Some…
- A child component receives a quantity prop and has plus and minus buttons. In Vue, how should the child…