]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
refactor(reactivity): improve shallowRef treeshaking
authorEvan You <evan@vuejs.org>
Wed, 29 Jan 2025 13:35:13 +0000 (21:35 +0800)
committerEvan You <evan@vuejs.org>
Wed, 29 Jan 2025 13:35:13 +0000 (21:35 +0800)
packages/reactivity/src/ref.ts

index ed868ff03208b9ae198bd14f2198865f1096f7f6..4de1de85d27ed75748f09786cdc7abc577ab7220 100644 (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,