Question presented to candidate:
"What do toRef and toRefs do in Vue 3, and what problem do they solve? Show me where you would use each, and what happens with a key that does not exist yet."
What a strong answer should cover:
toRef(obj, 'key')creates a ref that is a two-way link to one property of a reactive object: reading.valuereadsobj.key, writing.valuewrites it.toRefs(obj)does that for every property present at call time, returning a plain object of refs that can be destructured without losing reactivity.- Main uses: destructuring props in a plain
setup(props), returning reactive state from a composable so callers can destructure, and passing one property to a function that expects a ref. toRefsdoes not pick up keys added later;toRefworks for a missing key and can take a default value (3.2.25+).- Since 3.3,
toRef(() => getter)makes a readonly ref andtoValue()normalises a value, ref or getter. - Limits:
toRefson a plain object warns; refs from props orreadonlystay read-only.storeToRefsis the Pinia counterpart.
Clarifying questions expected:
- "Are we in
<script setup>, where props destructure is compiled since 3.5, or a plainsetup(props)function?" - "Is this about props, a composable's return value, or a store?"
Code / implementation expected: Yes β a child that destructures props both ways, and a composable that returns toRefs(state).