Question presented to candidate:
"Both computed and watch react to state changes in Vue. How do you decide which one to use? Give me an example where picking the wrong one causes a real bug."
What a strong answer should cover:
computedderives a value: it returns a read-only ref, is lazy (runs only when read), cached (re-runs only when a dependency changed) and should be a pure function.watchperforms a side effect when a source changes: fetching, logging, writing to storage, imperatively touching the DOM. It receives the new and old value and is lazy unlessimmediate: true.- A computed only notifies its dependents when its result changes (since Vue 3.4).
- Anti-patterns: a
watchthat copies a derived value into another ref (stale until the next flush, extra state), a computed with side effects, and anasynccomputed (its value is a Promise). - Watch callbacks are scheduled (flush
preby default); a computed is evaluated synchronously on read. - Options API equivalents are the
computedandwatchoptions; the reasoning is identical.
Clarifying questions expected:
- "Is the value needed in the template, or is the goal to trigger something outside Vue?"
- "Is any of the work asynchronous?"
Code / implementation expected: Yes — a filtered list with computed plus a watch that records each search.