mirror of https://github.com/vuejs/core.git
Merge 044b4d8a9a
into 56be3dd4db
This commit is contained in:
commit
c42f370f73
|
@ -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
|
||||
|
|
|
@ -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,
|
||||
|
|
Loading…
Reference in New Issue