Skip to content

fix(runtime-core): watching multiple sources: computed #3066

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

Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,33 @@ import {
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch

describe('api: watch', () => {
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++
})
watch(plus, () => {
count++
})
value.value = '2'
await nextTick()
expect(plus.value).toBe(true)
expect(count).toBe(0)
})

it('effect', async () => {
const state = reactive({ count: 0 })
let dummy
Expand Down
20 changes: 19 additions & 1 deletion packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,13 +167,15 @@ function doWatch(

let getter: () => any
let forceTrigger = false
let isSourceArray: boolean = false
if (isRef(source)) {
getter = () => (source as Ref).value
forceTrigger = !!(source as Ref)._shallow
} else if (isReactive(source)) {
getter = () => source
deep = true
} else if (isArray(source)) {
isSourceArray = true
getter = () =>
source.map(s => {
if (isRef(s)) {
Expand Down Expand Up @@ -248,7 +250,23 @@ function doWatch(
if (cb) {
// watch(source, cb)
const newValue = runner()
if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
let change: boolean = false

if (isSourceArray && isArray(newValue) && isArray(oldValue)) {
for (let i = 0; i < newValue.length && i < oldValue.length; i++) {
if (hasChanged(newValue[i], oldValue[i])) {
change = true
break
}
if (typeof newValue[i] === 'object') {
forceTrigger = true
break
}
}
} else {
change = hasChanged(newValue, oldValue)
}
if (deep || forceTrigger || change) {
// cleanup before running cb again
if (cleanup) {
cleanup()
Expand Down