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(runtime-core): handle useTemplateRef multiple calls #12883

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
15 changes: 10 additions & 5 deletions packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,23 @@ describe('useTemplateRef', () => {
expect(t1!.value).toBe(null)
})

test('should warn on duplicate useTemplateRef', () => {
test('should warn and return same value on duplicate useTemplateRef', async () => {
let f1, f2
const key = ref('foo')
const root = nodeOps.createElement('div')
render(
h(() => {
useTemplateRef('foo')
useTemplateRef('foo')
return ''
f1 = useTemplateRef('foo')
f2 = useTemplateRef('foo')
return h('div', { ref: key.value })
}),
root,
)

await nextTick()
expect(`useTemplateRef('foo') already exists.`).toHaveBeenWarned()
expect(f1!.value).toBe(root.children[0])
expect(f2!.value).toBe(root.children[0])
expect(f1!.value).toEqual(f2!.value)
})

// #11795
Expand Down
8 changes: 5 additions & 3 deletions packages/runtime-core/src/helpers/useTemplateRef.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ShallowRef, readonly, shallowRef } from '@vue/reactivity'
import { type ShallowRef, readonly, shallowRef, toRef } from '@vue/reactivity'
import { getCurrentInstance } from '../component'
import { warn } from '../warning'
import { EMPTY_OBJ } from '@vue/shared'
Expand All @@ -14,11 +14,13 @@ export function useTemplateRef<T = unknown, Keys extends string = string>(
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
let desc: PropertyDescriptor | undefined
if (
__DEV__ &&
(desc = Object.getOwnPropertyDescriptor(refs, key)) &&
!desc.configurable
) {
warn(`useTemplateRef('${key}') already exists.`)
if (__DEV__) {
warn(`useTemplateRef('${key}') already exists.`)
}
return toRef(() => refs[key]) as unknown as Readonly<ShallowRef<T>>
} else {
Object.defineProperty(refs, key, {
enumerable: true,
Expand Down