Skip to content

Commit fce2689

Browse files
committed
fix(watch): should trigger watcher callback on triggerRef when watching ref source
fix #1736
1 parent 09702e9 commit fce2689

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

packages/runtime-core/__tests__/apiWatch.spec.ts

+25-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@ import {
1212
ITERATE_KEY,
1313
DebuggerEvent,
1414
TrackOpTypes,
15-
TriggerOpTypes
15+
TriggerOpTypes,
16+
triggerRef
1617
} from '@vue/reactivity'
1718

1819
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
@@ -637,4 +638,27 @@ describe('api: watch', () => {
637638
v.value++
638639
expect(calls).toBe(1)
639640
})
641+
642+
test('should force trigger on triggerRef when watching a ref', async () => {
643+
const v = ref({ a: 1 })
644+
let sideEffect = 0
645+
watch(v, obj => {
646+
sideEffect = obj.a
647+
})
648+
649+
v.value = v.value
650+
await nextTick()
651+
// should not trigger
652+
expect(sideEffect).toBe(0)
653+
654+
v.value.a++
655+
await nextTick()
656+
// should not trigger
657+
expect(sideEffect).toBe(0)
658+
659+
triggerRef(v)
660+
await nextTick()
661+
// should trigger now
662+
expect(sideEffect).toBe(2)
663+
})
640664
})

packages/runtime-core/src/apiWatch.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -159,8 +159,9 @@ function doWatch(
159159
}
160160

161161
let getter: () => any
162-
if (isRef(source)) {
163-
getter = () => source.value
162+
const isRefSource = isRef(source)
163+
if (isRefSource) {
164+
getter = () => (source as Ref).value
164165
} else if (isReactive(source)) {
165166
getter = () => source
166167
deep = true
@@ -239,7 +240,7 @@ function doWatch(
239240
if (cb) {
240241
// watch(source, cb)
241242
const newValue = runner()
242-
if (deep || hasChanged(newValue, oldValue)) {
243+
if (deep || isRefSource || hasChanged(newValue, oldValue)) {
243244
// cleanup before running cb again
244245
if (cleanup) {
245246
cleanup()

0 commit comments

Comments
 (0)