Skip to content

Commit

Permalink
fix(watch): should trigger watcher callback on triggerRef when watchi…
Browse files Browse the repository at this point in the history
…ng ref source

fix #1736
  • Loading branch information
yyx990803 committed Jul 30, 2020
1 parent 09702e9 commit fce2689
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
26 changes: 25 additions & 1 deletion packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
ITERATE_KEY,
DebuggerEvent,
TrackOpTypes,
TriggerOpTypes
TriggerOpTypes,
triggerRef
} from '@vue/reactivity'

// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
Expand Down Expand Up @@ -637,4 +638,27 @@ describe('api: watch', () => {
v.value++
expect(calls).toBe(1)
})

test('should force trigger on triggerRef when watching a ref', async () => {
const v = ref({ a: 1 })
let sideEffect = 0
watch(v, obj => {
sideEffect = obj.a
})

v.value = v.value
await nextTick()
// should not trigger
expect(sideEffect).toBe(0)

v.value.a++
await nextTick()
// should not trigger
expect(sideEffect).toBe(0)

triggerRef(v)
await nextTick()
// should trigger now
expect(sideEffect).toBe(2)
})
})
7 changes: 4 additions & 3 deletions packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,9 @@ function doWatch(
}

let getter: () => any
if (isRef(source)) {
getter = () => source.value
const isRefSource = isRef(source)
if (isRefSource) {
getter = () => (source as Ref).value
} else if (isReactive(source)) {
getter = () => source
deep = true
Expand Down Expand Up @@ -239,7 +240,7 @@ function doWatch(
if (cb) {
// watch(source, cb)
const newValue = runner()
if (deep || hasChanged(newValue, oldValue)) {
if (deep || isRefSource || hasChanged(newValue, oldValue)) {

This comment has been minimized.

Copy link
@yangmingshan

yangmingshan Aug 3, 2020

Contributor

Is this condition necessary? The values ​​have been compared before the effect is triggered, right? I didn't see any chance this condition will be false, tell me if I'm wrong.

// cleanup before running cb again
if (cleanup) {
cleanup()
Expand Down

0 comments on commit fce2689

Please sign in to comment.