From: Evan You Date: Wed, 29 Jan 2025 13:35:13 +0000 (+0800) Subject: refactor(reactivity): improve shallowRef treeshaking X-Git-Tag: v3.6.0-alpha.1~16^2~125 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6979952613eb510c41022de296656a50c70c2ed0;p=thirdparty%2Fvuejs%2Fcore.git refactor(reactivity): improve shallowRef treeshaking --- diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index ed868ff032..4de1de85d2 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -58,7 +58,7 @@ export function ref( ): [T] extends [Ref] ? IfAny, T> : Ref, UnwrapRef | T> export function ref(): Ref export function ref(value?: unknown) { - return createRef(value, false) + return createRef(value, toReactive) } declare const ShallowRefMarker: unique symbol @@ -93,14 +93,14 @@ export function shallowRef( : ShallowRef export function shallowRef(): ShallowRef export function shallowRef(value?: unknown) { - return createRef(value, true) + return createRef(value) } -function createRef(rawValue: unknown, shallow: boolean) { +function createRef(rawValue: unknown, wrap?: (v: T) => T) { if (isRef(rawValue)) { return rawValue } - return new RefImpl(rawValue, shallow) + return new RefImpl(rawValue, wrap) } /** @@ -112,15 +112,17 @@ class RefImpl implements Dependency { subsTail: Link | undefined = undefined _value: T + _wrap?: (v: T) => T private _rawValue: T public readonly [ReactiveFlags.IS_REF] = true public readonly [ReactiveFlags.IS_SHALLOW]: boolean = false - constructor(value: T, isShallow: boolean) { - this._rawValue = isShallow ? value : toRaw(value) - this._value = isShallow ? value : toReactive(value) - this[ReactiveFlags.IS_SHALLOW] = isShallow + constructor(value: T, wrap: ((v: T) => T) | undefined) { + this._rawValue = wrap ? toRaw(value) : value + this._value = wrap ? wrap(value) : value + this._wrap = wrap + this[ReactiveFlags.IS_SHALLOW] = !wrap } get dep() { @@ -141,7 +143,8 @@ class RefImpl implements Dependency { newValue = useDirectValue ? newValue : toRaw(newValue) if (hasChanged(newValue, oldValue)) { this._rawValue = newValue - this._value = useDirectValue ? newValue : toReactive(newValue) + this._value = + this._wrap && !useDirectValue ? this._wrap(newValue) : newValue if (__DEV__) { triggerEventInfos.push({ target: this,