]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
fix(runtime-core): watching multiple sources: computed (#3066)
authorAbaAba~ <35401154+Kingbultsea@users.noreply.github.com>
Fri, 7 May 2021 22:03:35 +0000 (06:03 +0800)
committerGitHub <noreply@github.com>
Fri, 7 May 2021 22:03:35 +0000 (18:03 -0400)
fix #3068

packages/runtime-core/__tests__/apiWatch.spec.ts
packages/runtime-core/src/apiWatch.ts

index 0c3719e7364654cfab7b88c34eba5730b6afcd1b..aed7d65b6a55beb23c9164e63268a0df1faaad98 100644 (file)
@@ -944,4 +944,28 @@ describe('api: watch', () => {
     await nextTick()
     expect(spy).toHaveBeenCalledTimes(2)
   })
+  
+  it('watching sources: ref<any[]>', async () => {
+    const foo = ref([1])
+    const spy = jest.fn()
+    watch(foo, () => {
+      spy()
+    })
+    foo.value = foo.value.slice()
+    await nextTick()
+    expect(spy).toBeCalledTimes(1)
+  })
+
+  it('watching multiple sources: computed', async () => {
+    let count = 0
+    const value = ref('1')
+    const plus = computed(() => !!value.value)
+    watch([plus], () => {
+      count++
+    })
+    value.value = '2'
+    await nextTick()
+    expect(plus.value).toBe(true)
+    expect(count).toBe(0)
+  })
 })
index fa476f15dae976f3bff615a4f7c88ce645cebc2e..41ded87847a0b7f0b85cec378f622b50e3ec3b77 100644 (file)
@@ -171,6 +171,8 @@ function doWatch(
 
   let getter: () => any
   let forceTrigger = false
+  let isMultiSource = false
+
   if (isRef(source)) {
     getter = () => (source as Ref).value
     forceTrigger = !!(source as Ref)._shallow
@@ -178,6 +180,8 @@ function doWatch(
     getter = () => source
     deep = true
   } else if (isArray(source)) {
+    isMultiSource = true
+    forceTrigger = source.some(isReactive)
     getter = () =>
       source.map(s => {
         if (isRef(s)) {
@@ -265,7 +269,7 @@ function doWatch(
     return NOOP
   }
 
-  let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE
+  let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE
   const job: SchedulerJob = () => {
     if (!runner.active) {
       return
@@ -276,7 +280,11 @@ function doWatch(
       if (
         deep ||
         forceTrigger ||
-        hasChanged(newValue, oldValue) ||
+        (isMultiSource
+          ? (newValue as any[]).some((v, i) =>
+              hasChanged(v, (oldValue as any[])[i])
+            )
+          : hasChanged(newValue, oldValue)) ||
         (__COMPAT__ &&
           isArray(newValue) &&
           isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))