Skip to content

Commit

Permalink
fix(watch): always triggers when watching multiple refs (#791)
Browse files Browse the repository at this point in the history
* fix(watch): always triggers when watching multiple refs

* chore(apiwatch): use Object.js instead of ===

Co-authored-by: webfansplz <>
  • Loading branch information
webfansplz committed Aug 21, 2021
1 parent 3a1837f commit 8beffc3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/apis/watch.ts
Expand Up @@ -295,6 +295,7 @@ function createWatcher(
}

let deep = options.deep
let isMultiSource = false

let getter: () => any
if (isRef(source)) {
Expand All @@ -303,6 +304,7 @@ function createWatcher(
getter = () => source
deep = true
} else if (isArray(source)) {
isMultiSource = true
getter = () =>
source.map((s) => {
if (isRef(s)) {
Expand Down Expand Up @@ -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)
Expand Down
25 changes: 25 additions & 0 deletions test/apis/watch.spec.js
Expand Up @@ -5,6 +5,7 @@ const {
watch,
watchEffect,
set,
computed,
nextTick,
} = require('../../src')
const { mockWarn } = require('../helpers')
Expand Down Expand Up @@ -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)
})
})

0 comments on commit 8beffc3

Please sign in to comment.