Question presented to candidate:
"I have a <script setup> SearchField component and the parent page needs to focus it and clear it from a keyboard shortcut. I put ref="field" on it, but field.value.focus is undefined. What is defineExpose, and how would you use it here?"
What a strong answer should cover:
defineExpose({ ... })is a<script setup>compiler macro that lists what a parent can reach through a template ref on this component; nothing else is visible.- Typical exposed members are imperative methods:
focus(),clear(),validate(),open()/close(),scrollToTop(). - Exposed refs and computeds are unwrapped on the parent side (
field.value.lengthis a number, not a ref). - Rules: call it once, at the top level of
<script setup>; it compiles to theexpose()function from the setup context, anddefineOptionscannot declareexpose. - The parent can only use it after mount (the ref is
nullbefore), and in TypeScript the exposed shape is inferred, so calling a non-exposed member is a type error. - Prefer props and events for data; keep the exposed API small and command-shaped.
Clarifying questions expected:
- "Does the parent only need to trigger actions, or also read state from the child?"
- "Is the shortcut handled before the field is mounted, for example while it is behind a
v-if?"
Code / implementation expected: Yes β a child using defineExpose with one or two methods and a parent calling them through a template ref.