]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(ref): should not trigger when setting value to same proxy (#3658)
authorYang Mingshan <y.mingshan3@gmail.com>
Thu, 15 Jul 2021 20:28:01 +0000 (04:28 +0800)
committerGitHub <noreply@github.com>
Thu, 15 Jul 2021 20:28:01 +0000 (16:28 -0400)
packages/reactivity/__tests__/ref.spec.ts
packages/reactivity/src/ref.ts

index 883af0f874bc29ba68b329701748dfb2110ca40a..94ad47ec63d545d08be78c74418a2e43241b0f95 100644 (file)
@@ -336,4 +336,24 @@ describe('reactivity/ref', () => {
     _trigger!()
     expect(dummy).toBe(2)
   })
+
+  test('should not trigger when setting value to same proxy', () => {
+    const obj = reactive({ count: 0 })
+
+    const a = ref(obj)
+    const spy1 = jest.fn(() => a.value)
+
+    effect(spy1)
+
+    a.value = obj
+    expect(spy1).toBeCalledTimes(1)
+
+    const b = shallowRef(obj)
+    const spy2 = jest.fn(() => b.value)
+
+    effect(spy2)
+
+    b.value = obj
+    expect(spy2).toBeCalledTimes(1)
+  })
 })
index 3d1f1453ca1fc922e3865ccb00f187003f629085..1f6c93cacfac3d043339206b79247d8fcf179849 100644 (file)
@@ -52,12 +52,15 @@ export function shallowRef(value?: unknown) {
 }
 
 class RefImpl<T> {
+  private _rawValue: T
+
   private _value: T
 
   public readonly __v_isRef = true
 
-  constructor(private _rawValue: T, public readonly _shallow: boolean) {
-    this._value = _shallow ? _rawValue : convert(_rawValue)
+  constructor(value: T, public readonly _shallow = false) {
+    this._rawValue = _shallow ? value : toRaw(value)
+    this._value = _shallow ? value : convert(value)
   }
 
   get value() {
@@ -66,7 +69,8 @@ class RefImpl<T> {
   }
 
   set value(newVal) {
-    if (hasChanged(toRaw(newVal), this._rawValue)) {
+    newVal = this._shallow ? newVal : toRaw(newVal)
+    if (hasChanged(newVal, this._rawValue)) {
       this._rawValue = newVal
       this._value = this._shallow ? newVal : convert(newVal)
       trigger(toRaw(this), TriggerOpTypes.SET, 'value', newVal)