From 1aa1be4448200c3dff1f9fca7ca19ed2b879d8e8 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 7 Aug 2024 11:36:38 +0800 Subject: [PATCH] feat(reactivity): store value cache on CustomRefs impls --- packages/reactivity/__tests__/ref.spec.ts | 34 +++++++++++++++++++++++ packages/reactivity/src/ref.ts | 10 +++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/packages/reactivity/__tests__/ref.spec.ts b/packages/reactivity/__tests__/ref.spec.ts index f42281edd31..51a98bc2be2 100644 --- a/packages/reactivity/__tests__/ref.spec.ts +++ b/packages/reactivity/__tests__/ref.spec.ts @@ -467,4 +467,38 @@ describe('reactivity/ref', () => { expect(toValue(c)).toBe(3) expect(toValue(d)).toBe(4) }) + + test('ref w/ customRef w/ getterRef w/ objectRef should store value cache', () => { + const refValue = ref(1) + // @ts-expect-error private field + expect(refValue._value).toBe(1) + + let customRefValueCache = 0 + const customRefValue = customRef((track, trigger) => { + return { + get() { + track() + return customRefValueCache + }, + set(value: number) { + customRefValueCache = value + trigger() + }, + } + }) + customRefValue.value + + // @ts-expect-error internal field + expect(customRefValue._value).toBe(0) + + const getterRefValue = toRef(() => 1) + getterRefValue.value + // @ts-expect-error internal field + expect(getterRefValue._value).toBe(1) + + const objectRefValue = toRef({ value: 1 }, 'value') + objectRefValue.value + // @ts-expect-error internal field + expect(objectRefValue._value).toBe(1) + }) }) diff --git a/packages/reactivity/src/ref.ts b/packages/reactivity/src/ref.ts index 6e22d1bcd58..37f5d733a01 100644 --- a/packages/reactivity/src/ref.ts +++ b/packages/reactivity/src/ref.ts @@ -309,6 +309,8 @@ class CustomRefImpl { public readonly __v_isRef = true + public _value: T = undefined! + constructor(factory: CustomRefFactory) { const { get, set } = factory( () => trackRefValue(this), @@ -319,7 +321,7 @@ class CustomRefImpl { } get value() { - return this._get() + return (this._value = this._get()) } set value(newVal) { @@ -363,6 +365,7 @@ export function toRefs(object: T): ToRefs { class ObjectRefImpl { public readonly __v_isRef = true + public _value: T[K] = undefined! constructor( private readonly _object: T, @@ -372,7 +375,7 @@ class ObjectRefImpl { get value() { const val = this._object[this._key] - return val === undefined ? this._defaultValue! : val + return (this._value = val === undefined ? this._defaultValue! : val) } set value(newVal) { @@ -387,9 +390,10 @@ class ObjectRefImpl { class GetterRefImpl { public readonly __v_isRef = true public readonly __v_isReadonly = true + public _value: T = undefined! constructor(private readonly _getter: () => T) {} get value() { - return this._getter() + return (this._value = this._getter()) } }