Understanding Vue's Reactivity System: Building a Simple Reactivity Engine
This article explains Vue's reactivity system by recreating a simple reactivity engine using JavaScript, covering dependency collection, watcher functions, observer classes, and Object.defineProperty to track and update values automatically when data changes.
Many front‑end JavaScript frameworks such as Angular, React, and Vue implement their own data‑reactivity engines; grasping how reactivity works helps developers use these frameworks more effectively.
The problem illustrated is that when a Vue component’s price or quantity changes, Vue must automatically update the displayed price, recompute expressions like price * quantity , and recalculate totals, which ordinary JavaScript does not do.
The first solution introduces a global target that stores an anonymous function representing the code to run later, and a record function that pushes this target into an array; the solution can be written with ES6 arrow syntax.
Next, the article wraps this behaviour in a class, implementing a classic observer pattern: a class holds a list of dependent functions (targets) and notifies them when the observed data changes.
A Dep class is then created for each reactive property. Its depend() method registers the current target as a subscriber, and its notify() method runs all stored functions when the property’s setter is invoked.
Using Object.defineProperty() , getters and setters are defined for each data property. The getter records the current target, while the setter updates the internal value and calls dep.notify() , triggering all dependent watchers.
Finally, the article combines the target‑recording, class‑based observer, Dep instances, and Object.defineProperty logic into a complete code example that shows price and quantity reacting in real time, mirroring the illustration from Vue’s official documentation.
The summary of lessons learned includes how to create a Dep class for dependency collection, how to build a watcher/observer system, and how to use Object.defineProperty() to implement reactive getters and setters.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.