How computed and watch Work
🎯 Introduction
computed and watch are familiar Vue 2 APIs, but how are they implemented?
We return to the Vue 2.7.16 source to answer two questions: how computed caches values, and how watch implements immediate and deep. You will then be able to explain these APIs through their implementation and choose between them with a clear rationale.
vue@2.7.16 source. Run the small implementation examples with Node.js v22; no additional dependencies are required.🧱 Review: Both Use Watcher
Article 4 introduced Watcher, the reactivity system's subscriber. It evaluates a getter, tracks dependencies, and receives notifications when they change.
Neither API introduces a separate mechanism: both use Watcher, with different creation options:
computed: a lazy Watcher that defers evaluation and caches the result.watch: a user Watcher that invokes a user-provided callback when dependencies change.
Keep this distinction in mind as we read the source.
🧩 computed: A Lazy Watcher
During component initialization, initComputed creates a Watcher for each computed property:
// Simplified from initComputed in src/core/instance/state.js
function initComputed(vm, computed) {
const watchers = (vm._computedWatchers = Object.create(null));
for (const key in computed) {
const getter = computed[key];
// Each computed property has a lazy Watcher
watchers[key] = new Watcher(vm, getter, noop, { lazy: true });
if (!(key in vm)) {
defineComputed(vm, key, getter);
}
}
}
The key option is { lazy: true }. Here is how the Watcher constructor handles it:
// Simplified from the constructor in src/core/observer/watcher.js
constructor(vm, expOrFn, cb, options) {
this.vm = vm;
this.getter = expOrFn;
this.lazy = options.lazy;
this.dirty = this.lazy; // A lazy Watcher starts with dirty set to true
// Skip initial evaluation for lazy Watchers; value starts as undefined
this.value = this.lazy ? undefined : this.get();
}
An ordinary Watcher immediately evaluates this.get(). A lazy Watcher does not evaluate during creation; it sets dirty to true, indicating that its value has not yet been calculated.
🧠 Caching: The dirty Flag
defineComputed, called by initComputed, defines the property on vm. Accessing this.xxx invokes this getter:
// Simplified from defineComputed in src/core/instance/state.js
function defineComputed(target, key, userDef) {
Object.defineProperty(target, key, {
get() {
const watcher = target._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate(); // Evaluate only when dirty is true
}
return watcher.value; // Otherwise return the cached value
}
},
set() {},
});
}
The corresponding evaluate method is:
// Simplified from src/core/observer/watcher.js
evaluate() {
this.value = this.get(); // Execute the getter and store its result
this.dirty = false; // Mark the cached value as clean
}
The logic is straightforward:
- If
dirtyistrue, execute the getter, cache the result inwatcher.value, and setdirtytofalse. - If
dirtyisfalse, skip evaluation and returnwatcher.value.
Computed caching consists of a boolean dirty flag and a cached value. The first access calculates the value. Subsequent accesses return the cache as long as dependencies remain unchanged.
⚡ When Is the Cache Invalidated?
A computed property's cache must become invalid when its reactive dependencies change. Dep notifications call the Watcher's update method:
// Simplified from update in src/core/observer/watcher.js
update() {
if (this.lazy) {
// A lazy Watcher only sets dirty back to true; it does not evaluate yet
this.dirty = true;
} else {
this.run();
}
}
A dependency change does not immediately recalculate the value. It sets dirty back to true, marking the cache as stale. Recalculation happens the next time the computed property is accessed, through evaluate in its getter.
If data changes but the template does not use the computed property on that render, no unnecessary calculation runs.
By contrast, method calls in templates have no cache: each render that reaches the call executes the method again. This explains why computed properties suit derived values that benefit from caching.
🛠 watch: A Watcher and a Callback
initWatch processes the watch option, eventually delegating to vm.$watch:
// Simplified from $watch in src/core/instance/state.js
Vue.prototype.$watch = function (expOrFn, cb, options) {
const vm = this;
options = options || {};
options.user = true; // Mark this as a user Watcher
const watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value); // immediate: invoke once with the initial value
}
return function unwatchFn() {
watcher.teardown(); // Return a function that stops watching
};
};
The core is new Watcher(vm, expression, callback). Creating the Watcher evaluates the expression; for example, 'a.b' becomes a function that reads vm.a.b. This evaluation invokes reactive getters, tracking dependencies for the Watcher.
When dependencies change, the Watcher executes run:
// Simplified from run in src/core/observer/watcher.js
run() {
const value = this.get();
const oldValue = this.value;
this.value = value;
if (value !== oldValue || typeof value === 'object') {
this.cb.call(this.vm, value, oldValue); // cb(newVal, oldVal)
}
}
The comparison determines whether to invoke the callback with (newVal, oldVal). This is where the watch callback's two arguments come from.
🔍 How immediate and deep Work
immediate: Invoke Once After Creation
As the $watch code shows, immediate simply creates the Watcher, obtains its initial value, and immediately invokes the callback with it. It packages the common pattern of watching changes and also running the same logic during initialization.
deep: Traverse Nested Properties to Invoke Their Getters
Watcher handles deep inside get:
// Simplified from get in src/core/observer/watcher.js
get() {
pushTarget(this); // Set Dep.target to the current Watcher
let value = this.getter.call(this.vm, this.vm);
if (this.deep) {
traverse(value); // Recursively traverse the value
}
popTarget();
return value;
}
traverse recursively accesses the nested properties of the object or array:
// Simplified from src/core/observer/traverse.js
function traverse(val, seen = new Set()) {
if (typeof val !== 'object' || val === null || seen.has(val)) return;
seen.add(val); // Use a Set to avoid infinite traversal of circular references
if (Array.isArray(val)) {
val.forEach((item) => traverse(item, seen));
} else {
Object.keys(val).forEach((key) => traverse(val[key], seen));
}
}
Why read every nested property? Reactive getters track dependencies. Reading nested properties registers this Watcher with their Deps, allowing later nested changes to notify it.
This has a cost: larger, more deeply nested objects require more traversal and dependency tracking. Use deep for reasonably small structures; for large objects, prefer watching a specific path such as 'form.name'.
⚖️ Choosing Between Them
The implementation gives us a practical basis for choosing:
- Use computed for template values derived from other data. Caching avoids repeated calculation when dependencies have not changed, improving rendering efficiency.
- Use watch for side effects after data changes. Examples include asynchronous requests, localStorage operations, or expensive follow-up work. Computed getters should perform pure calculations rather than side effects.
A computed property derives a value; a watcher reacts to a change by doing work.
❓ Knowledge Check
Q1: Why does a computed property not recalculate immediately when a dependency changes?
A lazy Watcher only sets dirty to true when notified. Evaluation waits until the next property access, avoiding calculations whose results would never be used.
Q2: Methods and computed properties can both provide template values. How do they differ?
Computed properties cache their results until dependencies change. Methods have no such cache: each render that invokes a method executes it again.
Q3: Can watch detect nested object property changes without deep?
It does not generally track arbitrary nested mutations without deep traversal. Replacing the watched object triggers the watcher; deep uses traverse to track nested property Deps so nested changes can also trigger it.
Q4: Why are newVal and oldVal sometimes the same object in a watch callback?
When a nested property changes, both values may reference the same object rather than separate snapshots. The object check, typeof value === 'object', allows the callback to run even when the reference is unchanged, but both arguments still contain that same reference.
Q5: Is immediate different from watching and manually invoking the same logic during initialization?
The underlying idea is the same. immediate invokes the callback with the initial value after creating the Watcher, providing that common initialization pattern as an option.
🧪 Exercise
Using the dirty-flag caching approach and article 4's small Dep/Watcher implementation, complete a cached computed function. Run it with Node.js v22 and verify that repeated reads do not rerun the getter while dependencies remain unchanged.
// Small reactivity implementation: computed caching with a dirty flag
class Dep {
constructor() {
this.subs = [];
}
depend() {
if (Dep.target && !this.subs.includes(Dep.target)) {
this.subs.push(Dep.target);
}
}
notify() {
this.subs.forEach((w) => w.update());
}
}
Dep.target = null;
class Watcher {
constructor(getter, { lazy = false } = {}) {
this.getter = getter;
this.lazy = lazy;
this.dirty = lazy;
this.value = lazy ? undefined : this.get();
}
get() {
Dep.target = this;
const value = this.getter();
Dep.target = null;
return value;
}
evaluate() {
// Write your code here: evaluate and reset dirty
}
update() {
// Write your code here: for lazy Watchers, only set dirty to true
}
}
function defineReactive(obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
dep.depend();
return val;
},
set(newVal) {
val = newVal;
dep.notify();
},
});
}
function computed(vm, key, getter) {
const watcher = new Watcher(() => getter.call(vm), { lazy: true });
Object.defineProperty(vm, key, {
get() {
// Write your code here: evaluate only when dirty, then return watcher.value
},
});
}
// Verify the behavior
const state = { count: 1 };
defineReactive(state, 'count', 1);
const vm = { state };
computed(vm, 'double', function () {
console.log('getter executed');
return this.state.count * 2;
});
console.log(vm.double); // getter executed → 2
console.log(vm.double); // Cache hit; getter does not run again → 2
state.count = 10; // Notify dependencies and set dirty back to true
console.log(vm.double); // Recalculate → 20
🎉 You now understand how computed and watch work! Lazy Watchers, dirty-flag caching, immediate callbacks, and deep traversal all build on the same Watcher system.
