Преглед изворни кода

fix(watch): fix watching reactive array (#1656)

fixes #1655
Tan Li Hau пре 5 година
родитељ
комит
288b4eab9e

+ 10 - 0
packages/runtime-core/__tests__/apiWatch.spec.ts

@@ -69,6 +69,16 @@ describe('api: watch', () => {
     expect(dummy).toMatchObject([1, 0])
   })
 
+  it('watching single source: array', async () => {
+    const array = reactive([] as number[])
+    const spy = jest.fn()
+    watch(array, spy)
+    array.push(1)
+    await nextTick()
+    expect(spy).toBeCalledTimes(1)
+    expect(spy).toBeCalledWith([1], expect.anything(), expect.anything())
+  })
+
   it('watching single source: computed ref', async () => {
     const count = ref(0)
     const plus = computed(() => count.value + 1)

+ 6 - 6
packages/runtime-core/src/apiWatch.ts

@@ -159,7 +159,12 @@ function doWatch(
   }
 
   let getter: () => any
-  if (isArray(source)) {
+  if (isRef(source)) {
+    getter = () => source.value
+  } else if (isReactive(source)) {
+    getter = () => source
+    deep = true
+  } else if (isArray(source)) {
     getter = () =>
       source.map(s => {
         if (isRef(s)) {
@@ -172,11 +177,6 @@ function doWatch(
           __DEV__ && warnInvalidSource(s)
         }
       })
-  } else if (isRef(source)) {
-    getter = () => source.value
-  } else if (isReactive(source)) {
-    getter = () => source
-    deep = true
   } else if (isFunction(source)) {
     if (cb) {
       // getter with cb