All jobs / Frontend / web developer / Vue
Frontend / web developer interview question · 1–3 years
In Vue, when do you use a computed property and when a watcher?
The strongest answer
computed for values derived from other state — cached until a dependency changes; watch for side effects such as a request or saving a draft. Derived state kept in sync by a watcher is a smell
Why it works
Exactly — derive with computed, react with watch. A watcher that only copies state into other state is a computed waiting to be written.
What a good answer covers
- Derive with computed, react with watch.
- computed: cached, pure, returns a value.
- watch: side effects on change.
- No fetches during render.
Answers that fall short
- Close, but not the strongest: computed gives back a value and watch runs some code when a value changes; I pick by feel
True as far as it goes; the interviewer wants caching, dependencies, and the side-effect rule. - Weak: They are interchangeable, so I use watch everywhere and assign the result to another ref
Watch-and-assign creates a second source of truth that lags a tick and is easy to get out of sync. - Red flag: A method called from the template, doing the fetch inside it each time it renders
A fetch inside render fires on every re-render and can loop; rendering must stay free of side effects.
Who gets asked this
More Vue questions
- 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…
- In a Vue 3 component using script setup, you try to focus an input through a template ref at the top of setup…
- In setup, a developer writes const { count } = state, where state is a reactive object. The template shows…