Skip to content

Commit 3e68a1b

Browse files
committed
fix: ensure template ref cleanup passes null and deletes WeakMap entry
1 parent bb0e242 commit 3e68a1b

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

packages/runtime-vapor/__tests__/dom/templateRef.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ describe('api: template ref', () => {
182182
expect(fn.mock.calls[0][0]).toBe(host.children[0])
183183
toggle.value = false
184184
await nextTick()
185-
expect(fn.mock.calls[1][0]).toBe(undefined)
185+
expect(fn.mock.calls[1][0]).toBe(null)
186186
})
187187

188188
test('useTemplateRef mount', () => {

packages/runtime-vapor/src/apiTemplateRef.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,6 @@ import {
2525
} from '@vue/shared'
2626
import { DynamicFragment, isFragment } from './fragment'
2727

28-
// track cleanup functions to prevent duplicate onScopeDispose registrations
29-
const refCleanups = new WeakMap<RefEl, { fn: () => void }>()
30-
31-
// ensure only register onScopeDispose once per element
32-
function ensureCleanup(el: RefEl): { fn: () => void } {
33-
let cleanupRef = refCleanups.get(el)
34-
if (!cleanupRef) {
35-
refCleanups.set(el, (cleanupRef = { fn: NOOP }))
36-
onScopeDispose(() => cleanupRef!.fn())
37-
}
38-
return cleanupRef
39-
}
40-
4128
export type NodeRef =
4229
| string
4330
| Ref
@@ -52,6 +39,20 @@ export type setRefFn = (
5239
refKey?: string,
5340
) => NodeRef | undefined
5441

42+
const refCleanups = new WeakMap<RefEl, { fn: () => void }>()
43+
44+
function ensureCleanup(el: RefEl): { fn: () => void } {
45+
let cleanupRef = refCleanups.get(el)
46+
if (!cleanupRef) {
47+
refCleanups.set(el, (cleanupRef = { fn: NOOP }))
48+
onScopeDispose(() => {
49+
cleanupRef!.fn()
50+
refCleanups.delete(el)
51+
})
52+
}
53+
return cleanupRef
54+
}
55+
5556
export function createTemplateRefSetter(): setRefFn {
5657
const instance = currentInstance as VaporComponentInstance
5758
return (...args) => setRef(instance, ...args)
@@ -108,15 +109,15 @@ export function setRef(
108109
}
109110

110111
if (isFunction(ref)) {
111-
const invokeRefSetter = (value?: Element | Record<string, any>) => {
112+
const invokeRefSetter = (value?: Element | Record<string, any> | null) => {
112113
callWithErrorHandling(ref, currentInstance, ErrorCodes.FUNCTION_REF, [
113114
value,
114115
refs,
115116
])
116117
}
117118

118119
invokeRefSetter(refValue)
119-
ensureCleanup(el).fn = () => invokeRefSetter()
120+
ensureCleanup(el).fn = () => invokeRefSetter(null)
120121
} else {
121122
const _isString = isString(ref)
122123
const _isRef = isRef(ref)

0 commit comments

Comments
 (0)