Skip to content
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

fix(reactivity): triggerRef working with toRef from reactive #7507

Merged
merged 4 commits into from Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/reactivity/src/effect.ts
Expand Up @@ -377,3 +377,7 @@ function triggerEffect(
}
}
}

export function getDepFromReactive(object: any, key: string | number | symbol) {
return targetMap.get(object)?.get(key)
}
12 changes: 9 additions & 3 deletions packages/reactivity/src/ref.ts
@@ -1,5 +1,6 @@
import {
activeEffect,
getDepFromReactive,
shouldTrack,
trackEffects,
triggerEffects
Expand Down Expand Up @@ -53,16 +54,17 @@ export function trackRefValue(ref: RefBase<any>) {

export function triggerRefValue(ref: RefBase<any>, newVal?: any) {
ref = toRaw(ref)
if (ref.dep) {
const dep = ref.dep
if (dep) {
if (__DEV__) {
triggerEffects(ref.dep, {
triggerEffects(dep, {
target: ref,
type: TriggerOpTypes.SET,
key: 'value',
newValue: newVal
})
} else {
triggerEffects(ref.dep)
triggerEffects(dep)
}
}
}
Expand Down Expand Up @@ -228,6 +230,10 @@ class ObjectRefImpl<T extends object, K extends keyof T> {
set value(newVal) {
this._object[this._key] = newVal
}

get dep(): Dep | undefined {
return getDepFromReactive(toRaw(this._object), this._key)
}
}

export type ToRef<T> = IfAny<T, Ref<T>, [T] extends [Ref] ? T : Ref<T>>
Expand Down
22 changes: 21 additions & 1 deletion packages/runtime-core/__tests__/apiWatch.spec.ts
Expand Up @@ -29,7 +29,8 @@ import {
triggerRef,
shallowRef,
Ref,
effectScope
effectScope,
toRef
} from '@vue/reactivity'

// reference: https://vue-composition-api-rfc.netlify.com/api.html#watch
Expand Down Expand Up @@ -925,6 +926,25 @@ describe('api: watch', () => {
expect(spy).toHaveBeenCalledTimes(1)
})

test('should force trigger on triggerRef with toRef from reactive', async () => {
const foo = reactive({ bar: 1 })
const bar = toRef(foo, 'bar')
const spy = jest.fn()

watchEffect(() => {
bar.value
spy()
})

expect(spy).toHaveBeenCalledTimes(1)

triggerRef(bar)

await nextTick()
// should trigger now
expect(spy).toHaveBeenCalledTimes(2)
})

// #2125
test('watchEffect should not recursively trigger itself', async () => {
const spy = jest.fn()
Expand Down