From 8beffc3c9c5fd4c2a86f4ec8a29ef00cac4d6912 Mon Sep 17 00:00:00 2001 From: webfansplz <308241863@qq.com> Date: Sat, 21 Aug 2021 16:37:40 +0800 Subject: [PATCH] fix(watch): always triggers when watching multiple refs (#791) * fix(watch): always triggers when watching multiple refs * chore(apiwatch): use Object.js instead of === Co-authored-by: webfansplz <> --- src/apis/watch.ts | 4 ++++ test/apis/watch.spec.js | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/apis/watch.ts b/src/apis/watch.ts index 9c165f58..83522aed 100644 --- a/src/apis/watch.ts +++ b/src/apis/watch.ts @@ -295,6 +295,7 @@ function createWatcher( } let deep = options.deep + let isMultiSource = false let getter: () => any if (isRef(source)) { @@ -303,6 +304,7 @@ function createWatcher( getter = () => source deep = true } else if (isArray(source)) { + isMultiSource = true getter = () => source.map((s) => { if (isRef(s)) { @@ -339,6 +341,8 @@ function createWatcher( } const applyCb = (n: any, o: any) => { + if (isMultiSource && n.every((v: any, i: number) => Object.is(v, o[i]))) + return // cleanup before running cb again runCleanup() return cb(n, o, registerCleanup) diff --git a/test/apis/watch.spec.js b/test/apis/watch.spec.js index 0bb8aeb9..e01b3c3d 100644 --- a/test/apis/watch.spec.js +++ b/test/apis/watch.spec.js @@ -5,6 +5,7 @@ const { watch, watchEffect, set, + computed, nextTick, } = require('../../src') const { mockWarn } = require('../helpers') @@ -821,4 +822,28 @@ describe('api/watch', () => { expect(cb).toHaveBeenCalled() }) + + it('watching sources: ref<[]>', async () => { + const foo = ref([1]) + const cb = jest.fn() + watch(foo, cb) + foo.value = foo.value.slice() + await nextTick() + expect(cb).toBeCalledTimes(1) + }) + + it('watching multiple sources: computed', async () => { + const number = ref(1) + const div2 = computed(() => { + return number.value > 2 ? '>2' : '<=2' + }) + const div3 = computed(() => { + return number.value > 3 ? '>3' : '<=3' + }) + const cb = jest.fn() + watch([div2, div3], cb) + number.value = 2 + await nextTick() + expect(cb).toHaveBeenCalledTimes(0) + }) })