refactor(reactivity): improve shallowRef treeshaking

This commit is contained in:
Evan You 2025-01-29 21:35:13 +08:00
parent 181d3403f7
commit 6979952613
No known key found for this signature in database
GPG Key ID: 00E9AB7A6704CE0A
1 changed files with 12 additions and 9 deletions

View File

@ -58,7 +58,7 @@ export function ref<T>(
): [T] extends [Ref] ? IfAny<T, Ref<T>, T> : Ref<UnwrapRef<T>, UnwrapRef<T> | T>
export function ref<T = any>(): Ref<T | undefined>
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<T>(
: ShallowRef<T>
export function shallowRef<T = any>(): ShallowRef<T | undefined>
export function shallowRef(value?: unknown) {
return createRef(value, true)
return createRef(value)
}
function createRef(rawValue: unknown, shallow: boolean) {
function createRef(rawValue: unknown, wrap?: <T>(v: T) => T) {
if (isRef(rawValue)) {
return rawValue
}
return new RefImpl(rawValue, shallow)
return new RefImpl(rawValue, wrap)
}
/**
@ -112,15 +112,17 @@ class RefImpl<T = any> implements Dependency {
subsTail: Link | undefined = undefined
_value: T
_wrap?: <T>(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: (<T>(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<T = any> 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,