This commit is contained in:
Konv Suu 2025-05-05 20:38:37 +00:00 committed by GitHub
commit c42f370f73
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 8 deletions

View File

@ -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

View File

@ -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'
@ -16,11 +16,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,