The implementation principle of vue. js 3.0 responsive system
A targetMap is maintained internally to record the object and its attributes, as well as the corresponding update operation function when the attributes change. When intercepting object operations through Proxy, track collection dependencies will be called when intercepting GET operations, and trigger will be called when intercepting SET and deleteProperty operations to trigger updates
TargetMap is used to record the mapping between an object and an attribute: key is target, value is a depsMap; DepsMap records the mapping between attributes and a set of update functions: key is the accessed attribute, value is a DEP set; The DEP holds a set of ActiveEffects, which are the actions that need to be performed for the update
const product = reactive({ price: 100, count: 3}) let total = 0 effect(() => {total = product.price * product.count}) product => depsMap => { price => dep count => dep } price => dep => [ () => {total = product.price * product.count} ] count => dep => [ () => {total = product.price * product.count} ]
- Call Reactive to pass in objects that need to be processed in a reactive manner, intercept objects through Proxy internally, and return objects that are brokered by new Proxy
- When accessing object properties, the get operation is intercepted, track is called to collect dependencies, and then the value of the property is obtained to determine whether the value of the property is an object. If so, reactive is called to achieve recursion of the sub-object
- Track Receives objects and accesses properties
(target, key)
, check whether the current activeEffect is available. ActiveEffect is a callback function that is set to update in the effect function. If not, return. Select depsMap from targetMap and set a new Map.targetMap.set(target, (depsMap = new Map()))
Select depsMap from depsMap and Set a new Set.depsMap.set(key, (dep = new Set()))
Finally, add activeEffects to the DEPdep.add(activeEffect)
- When setting or deleting object properties, the set and deleteProperty operations are intercepted and trigger is called to trigger the update
- Trigger Receives objects and accesses properties
(target, key)
Select depsMap from targetMap and return depsMap from targetMap. Select deP from depsMap and return deP from depsMap with keyeffect()