Skip to content

Commit 3ac052b

Browse files
authored
fix(runtime-core): pause tracking when invoking function refs (#14985)
1 parent e450973 commit 3ac052b

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

‎packages/runtime-core/__tests__/rendererTemplateRef.spec.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,26 @@ describe('api: template refs', () => {
111111
expect(fn2.mock.calls[0][0]).toBe(root.children[0])
112112
})
113113

114+
it('function ref should not track dependencies read by callback', async () => {
115+
const root = nodeOps.createElement('div')
116+
const visible = ref(new Set<number>())
117+
const fn = vi.fn((el: any) => {
118+
if (!el || visible.value.has(0)) {
119+
return
120+
}
121+
visible.value = new Set([0])
122+
})
123+
124+
const Comp = defineComponent(() => () => h('div', { ref: fn }))
125+
126+
render(h(Comp), root)
127+
expect(fn).toHaveBeenCalledTimes(1)
128+
expect(visible.value.has(0)).toBe(true)
129+
130+
await nextTick()
131+
expect(fn).toHaveBeenCalledTimes(1)
132+
})
133+
114134
it('function ref unmount', async () => {
115135
const root = nodeOps.createElement('div')
116136
const fn = vi.fn()

‎packages/runtime-core/src/rendererTemplateRef.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
} from '@vue/shared'
1818
import { isAsyncWrapper } from './apiAsyncComponent'
1919
import { warn } from './warning'
20-
import { isRef, toRaw } from '@vue/reactivity'
20+
import { isRef, pauseTracking, resetTracking, toRaw } from '@vue/reactivity'
2121
import { ErrorCodes, callWithErrorHandling } from './errorHandling'
2222
import { type SchedulerJob, SchedulerJobFlags } from './scheduler'
2323
import { queuePostRenderEffect } from './renderer'
@@ -136,7 +136,12 @@ export function setRef(
136136
}
137137

138138
if (isFunction(ref)) {
139-
callWithErrorHandling(ref, owner, ErrorCodes.FUNCTION_REF, [value, refs])
139+
pauseTracking()
140+
try {
141+
callWithErrorHandling(ref, owner, ErrorCodes.FUNCTION_REF, [value, refs])
142+
} finally {
143+
resetTracking()
144+
}
140145
} else {
141146
const _isString = isString(ref)
142147
const _isRef = isRef(ref)

0 commit comments

Comments
 (0)