Vue.js Developer interview question · Most asked
How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
Summary
Vue 3 wraps objects in JavaScript Proxies: reading a property inside an effect (a component render, computed, watchEffect) records a dependency (track), and writing the property re-runs the effects that depend on it (trigger). Vue 2 used Object.defineProperty getters and setters, which could not detect added or deleted properties or array index assignments.
Longer Answer
In Vue 2 you needed Vue.set(obj, 'newKey', value) and array mutation methods because obj.newKey = 1 and arr[0] = x were invisible to reactivity. Proxies intercept all of these, plus Map, Set, in and delete, so Vue 3 removed Vue.set/Vue.delete.
Dependencies are tracked per property, so updates are fine-grained: changing user.name only re-renders components that read user.name. Effects are batched and applied asynchronously before the next paint, which is why nextTick() is needed to read the updated DOM.
Key Points
- Proxies: track on read, trigger on write.
- Vue 2 defineProperty missed new keys/array indexes.
- Fine-grained per-property dependencies.
- Batched async updates; nextTick.
Explanation
What interviewers look for
Understanding of track/trigger and the Vue 2 caveats it removed.
More most-asked Vue.js Developer questions
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- What are composables, and why did they replace mixins?
- computed, watch or watchEffect: when do you use each?
- Options API or Composition API: what is the difference, and which would you use?
- ref or reactive: what is the difference, and when do you use each?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?