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; }, }); }
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); }
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(); }
DOM 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! 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 function trigger(target, key) {
let depsMap = targetMap.get(target);
let dep = depsMap.get(key);
for (let effect of dep) {
effect.fn();
}
}