Skip to content

Commit 8beffc3

Browse files
authoredAug 21, 2021
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 <>
1 parent 3a1837f commit 8beffc3

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed
 

‎src/apis/watch.ts

+4
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,7 @@ function createWatcher(
295295
}
296296

297297
let deep = options.deep
298+
let isMultiSource = false
298299

299300
let getter: () => any
300301
if (isRef(source)) {
@@ -303,6 +304,7 @@ function createWatcher(
303304
getter = () => source
304305
deep = true
305306
} else if (isArray(source)) {
307+
isMultiSource = true
306308
getter = () =>
307309
source.map((s) => {
308310
if (isRef(s)) {
@@ -339,6 +341,8 @@ function createWatcher(
339341
}
340342

341343
const applyCb = (n: any, o: any) => {
344+
if (isMultiSource && n.every((v: any, i: number) => Object.is(v, o[i])))
345+
return
342346
// cleanup before running cb again
343347
runCleanup()
344348
return cb(n, o, registerCleanup)

‎test/apis/watch.spec.js

+25
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const {
55
watch,
66
watchEffect,
77
set,
8+
computed,
89
nextTick,
910
} = require('../../src')
1011
const { mockWarn } = require('../helpers')
@@ -821,4 +822,28 @@ describe('api/watch', () => {
821822

822823
expect(cb).toHaveBeenCalled()
823824
})
825+
826+
it('watching sources: ref<[]>', async () => {
827+
const foo = ref([1])
828+
const cb = jest.fn()
829+
watch(foo, cb)
830+
foo.value = foo.value.slice()
831+
await nextTick()
832+
expect(cb).toBeCalledTimes(1)
833+
})
834+
835+
it('watching multiple sources: computed', async () => {
836+
const number = ref(1)
837+
const div2 = computed(() => {
838+
return number.value > 2 ? '>2' : '<=2'
839+
})
840+
const div3 = computed(() => {
841+
return number.value > 3 ? '>3' : '<=3'
842+
})
843+
const cb = jest.fn()
844+
watch([div2, div3], cb)
845+
number.value = 2
846+
await nextTick()
847+
expect(cb).toHaveBeenCalledTimes(0)
848+
})
824849
})

0 commit comments

Comments
 (0)
Please sign in to comment.