You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
exportfunctioncomputed<T>(getterOrOptions: ComputedGetter<T>|WritableComputedOptions<T>,debugOptions?: DebuggerOptions){
let getter: ComputedGetter<T>letsetter: ComputedSetter<T>// 1. 函数初始化constonlyGetter=isFunction(getterOrOptions)if(onlyGetter){getter=getterOrOptionssetter=__DEV__
? ()=>{console.warn('Write operation failed: computed value is readonly')}
: NOOP}else{getter=getterOrOptions.getsetter=getterOrOptions.set}// 2. computed对象constcRef=newComputedRefImpl(getter,setter,onlyGetter||!setter)if(__DEV__&&debugOptions){cRef.effect.onTrack=debugOptions.onTrackcRef.effect.onTrigger=debugOptions.onTrigger}returncRefasany}
classComputedRefImpl<T>{publicdep?: Dep=undefinedprivate_value!: Tprivate_dirty=truepublicreadonlyeffect: ReactiveEffect<T>publicreadonly__v_isRef=truepublicreadonly[ReactiveFlags.IS_READONLY]: booleanconstructor(getter: ComputedGetter<T>,privatereadonly_setter: ComputedSetter<T>,isReadonly: boolean){this.effect=newReactiveEffect(getter,()=>{if(!this._dirty){this._dirty=truetriggerRefValue(this)}})this[ReactiveFlags.IS_READONLY]=isReadonly}getvalue(){// the computed ref may get wrapped by other proxies e.g. readonly() #3376constself=toRaw(this)trackRefValue(self)if(self._dirty){self._dirty=falseself._value=self.effect.run()!}returnself._value}setvalue(newValue: T){this._setter(newValue)}}
exportclassReactiveEffect<T=any>{active=truedeps: Dep[]=[]// can be attached after creationcomputed?: booleanallowRecurse?: booleanonStop?: ()=>void// ...constructor(publicfn: ()=>T,publicscheduler: EffectScheduler|null=null,scope?: EffectScope|null){recordEffectScope(this,scope)}run(){// ...}stop(){if(this.active){cleanupEffect(this)if(this.onStop){this.onStop()}this.active=false}}}
getvalue(){// the computed ref may get wrapped by other proxies e.g. readonly() #3376constself=toRaw(this)trackRefValue(self)if(self._dirty){self._dirty=falseself._value=self.effect.run()!}returnself._value}
computed函数第一个参数可能是函数或者是对象,第一步进行判断对computed进行初始化处理;
传入getter, setter, 和是否只读(只有getter)初始化computed对象;
computed对象重要属性:
_value
: 值dirty
: 是否是脏的,判断是否需要再次计算effect
: 响应式回调再看回构造函数,初始化了effect,如果数据不是脏的,就将dirty修改为true,并
triggerRefValue
ReactiveEffect:
构造函数传入fn, scheduler, 域
执行函数run
get函数:
组件渲染阶段触发get函数, 如果数据是脏的就修改为true, 然后调用effect的执行函数run修改value
The text was updated successfully, but these errors were encountered: