Home > Article > Web Front-end > What is the principle of vue3 reactive responsive dependency collection, dispatch and update?
Object.property to
Proxy,
ProxyCompared with the former, you can directly monitor object arrays. For deep-level objects and arrays, the triggers will be mapped to
getter, and then recursively collect dependencies. It is not directly violent like
vue2 That kind of recursion has better overall performance
function reactive(raw) { return new Proxy(raw, { get(target, key) { const res = Reflect.get(target, key); //添加依赖 track(target, key as string); return res; }, set(target, key, value) { const res = Reflect.set(target, key, value); trigger(target, key); return res; }, }); }Use
Reflet to standardize the object, because if JS is used directly and fails, no exception prompt will be generated
const targetMap = new WeakMap(); function track(target, key) { let depsMap = targetMap.get(target); if (!depsMap) { depsMap = new Map(); targetMap.set(target, depsMap); } let dep = depsMap.get(key); if (!dep) { dep = new Set(); depsMap.set(key, dep); } dep.add(currentEffect); }First it is a WeakMap-->Then the user gets the corresponding response through the target The internal Map-->Then the Set collection is obtained through the key, and the internal dependencies are stored one by one. In fact, this is the process of dependency collection. The reason WeakMap is used here is that it is a weak reference and will not affect the garbage collection mechanism. currentEffectSo what is
currentEffect? In fact, it is the running class in
ReactiveEffect
class ReactiveEffect { private fn: Function; constructor(_fn: Function) { this.fn = _fn; } run() { currentEffect = this; this.fn(); } } let currentEffect: null | ReactiveEffect = null; function effect(fn: Function) { const reactiveEffect = new ReactiveEffect(fn); reactiveEffect.run(); }will be explained in detail later. For now, it can be understood as a dependency. After the user uses the effect function, the responsive data inside it occurs. After the change, the callback function passed in will be re-executed The dependencies collected in vue2 correspond to watchers, and the dependencies collected in vue3 are actually effects. The functions they implement are actually the same. Distribute updatesIgnore the
DOM issue for now. The operation is actually very simple, just pass the
target## hijacked by Proxy
#Find the corresponding Set collection with key
and call the fn
function passed by the user to update the dependency <pre class="brush:js;">function trigger(target, key) {
let depsMap = targetMap.get(target);
let dep = depsMap.get(key);
for (let effect of dep) {
effect.fn();
}
}</pre>
The above is the detailed content of What is the principle of vue3 reactive responsive dependency collection, dispatch and update?. For more information, please follow other related articles on the PHP Chinese website!