Skip to content

fix(runtime-core): unset old ref during patching when new ref is absent #12900

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

Merged
merged 4 commits into from
Jun 5, 2025
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/runtime-core/__tests__/rendererTemplateRef.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,37 @@ describe('api: template refs', () => {
expect(el.value).toBe(null)
})

it('unset old ref when new ref is absent', async () => {
const root1 = nodeOps.createElement('div')
const root2 = nodeOps.createElement('div')
const el1 = ref(null)
const el2 = ref(null)
const toggle = ref(true)

const Comp1 = {
setup() {
return () => (toggle.value ? h('div', { ref: el1 }) : h('div'))
},
}

const Comp2 = {
setup() {
return () => h('div', { ref: toggle.value ? el2 : undefined })
},
}

render(h(Comp1), root1)
render(h(Comp2), root2)

expect(el1.value).toBe(root1.children[0])
expect(el2.value).toBe(root2.children[0])

toggle.value = false
await nextTick()
expect(el1.value).toBe(null)
expect(el2.value).toBe(null)
})

test('string ref inside slots', async () => {
const root = nodeOps.createElement('div')
const spy = vi.fn()
Expand Down
2 changes: 2 additions & 0 deletions packages/runtime-core/src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,8 @@ function baseCreateRenderer(
// set ref
if (ref != null && parentComponent) {
setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2)
} else if (ref == null && n1 && n1.ref != null) {
setRef(n1.ref, null, parentSuspense, n1, true)
}
}

Expand Down