Skip to content

Commit e64c9ae

Browse files
authored
fix(reactivity): triggerRef working with toRef from reactive (#7507)
* fix(reactivity): `triggerRef` working with `toRef` from reactive * chore: refactor
1 parent 5f1883e commit e64c9ae

File tree

3 files changed

+34
-4
lines changed

3 files changed

+34
-4
lines changed

packages/reactivity/src/effect.ts

+4
Original file line numberDiff line numberDiff line change
@@ -377,3 +377,7 @@ function triggerEffect(
377377
}
378378
}
379379
}
380+
381+
export function getDepFromReactive(object: any, key: string | number | symbol) {
382+
return targetMap.get(object)?.get(key)
383+
}

packages/reactivity/src/ref.ts

+9-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
activeEffect,
3+
getDepFromReactive,
34
shouldTrack,
45
trackEffects,
56
triggerEffects
@@ -53,16 +54,17 @@ export function trackRefValue(ref: RefBase<any>) {
5354

5455
export function triggerRefValue(ref: RefBase<any>, newVal?: any) {
5556
ref = toRaw(ref)
56-
if (ref.dep) {
57+
const dep = ref.dep
58+
if (dep) {
5759
if (__DEV__) {
58-
triggerEffects(ref.dep, {
60+
triggerEffects(dep, {
5961
target: ref,
6062
type: TriggerOpTypes.SET,
6163
key: 'value',
6264
newValue: newVal
6365
})
6466
} else {
65-
triggerEffects(ref.dep)
67+
triggerEffects(dep)
6668
}
6769
}
6870
}
@@ -228,6 +230,10 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
228230
set value(newVal) {
229231
this._object[this._key] = newVal
230232
}
233+
234+
get dep(): Dep | undefined {
235+
return getDepFromReactive(toRaw(this._object), this._key)
236+
}
231237
}
232238

233239
export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>>

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

+21-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ import {
3030
triggerRef,
3131
shallowRef,
3232
Ref,
33-
effectScope
33+
effectScope,
34+
toRef
3435
} from '@vue/reactivity'
3536

3637
// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
@@ -926,6 +927,25 @@ describe('api: watch', () => {
926927
expect(spy).toHaveBeenCalledTimes(1)
927928
})
928929

930+
test('should force trigger on triggerRef with toRef from reactive', async () => {
931+
const foo = reactive({ bar: 1 })
932+
const bar = toRef(foo, 'bar')
933+
const spy = jest.fn()
934+
935+
watchEffect(() => {
936+
bar.value
937+
spy()
938+
})
939+
940+
expect(spy).toHaveBeenCalledTimes(1)
941+
942+
triggerRef(bar)
943+
944+
await nextTick()
945+
// should trigger now
946+
expect(spy).toHaveBeenCalledTimes(2)
947+
})
948+
929949
// #2125
930950
test('watchEffect should not recursively trigger itself', async () => {
931951
const spy = vi.fn()

0 commit comments

Comments
 (0)