Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(watch): always triggers when watching multiple refs #791

Merged
merged 2 commits into from Aug 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
})
})