Skip to content

Commit

Permalink
fix(runtime-core): watching multiple sources: computed (#3066)
Browse files Browse the repository at this point in the history
fix #3068
  • Loading branch information
Kingbultsea committed May 7, 2021
1 parent 349eb0f commit e7300eb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
24 changes: 24 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -944,4 +944,28 @@ describe('api: watch', () => {
await nextTick()
expect(spy).toHaveBeenCalledTimes(2)
})

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++
})
value.value = '2'
await nextTick()
expect(plus.value).toBe(true)
expect(count).toBe(0)
})
})
12 changes: 10 additions & 2 deletions packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,13 +171,17 @@ function doWatch(

let getter: () => any
let forceTrigger = false
let isMultiSource = 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)) {
isMultiSource = true
forceTrigger = source.some(isReactive)
getter = () =>
source.map(s => {
if (isRef(s)) {
Expand Down Expand Up @@ -265,7 +269,7 @@ function doWatch(
return NOOP
}

let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE
let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE
const job: SchedulerJob = () => {
if (!runner.active) {
return
Expand All @@ -276,7 +280,11 @@ function doWatch(
if (
deep ||
forceTrigger ||
hasChanged(newValue, oldValue) ||
(isMultiSource
? (newValue as any[]).some((v, i) =>
hasChanged(v, (oldValue as any[])[i])
)
: hasChanged(newValue, oldValue)) ||
(__COMPAT__ &&
isArray(newValue) &&
isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))
Expand Down

0 comments on commit e7300eb

Please sign in to comment.