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)
|
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')
|
const root = nodeOps.createElement('div')
|
||||||
render(
|
render(
|
||||||
h(() => {
|
h(() => {
|
||||||
useTemplateRef('foo')
|
f1 = useTemplateRef('foo')
|
||||||
useTemplateRef('foo')
|
f2 = useTemplateRef('foo')
|
||||||
return ''
|
return h('div', { ref: key.value })
|
||||||
}),
|
}),
|
||||||
root,
|
root,
|
||||||
)
|
)
|
||||||
|
await nextTick()
|
||||||
expect(`useTemplateRef('foo') already exists.`).toHaveBeenWarned()
|
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
|
// #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 { getCurrentInstance } from '../component'
|
||||||
import { warn } from '../warning'
|
import { warn } from '../warning'
|
||||||
import { EMPTY_OBJ } from '@vue/shared'
|
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
|
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
|
||||||
let desc: PropertyDescriptor | undefined
|
let desc: PropertyDescriptor | undefined
|
||||||
if (
|
if (
|
||||||
__DEV__ &&
|
|
||||||
(desc = Object.getOwnPropertyDescriptor(refs, key)) &&
|
(desc = Object.getOwnPropertyDescriptor(refs, key)) &&
|
||||||
!desc.configurable
|
!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 {
|
} else {
|
||||||
Object.defineProperty(refs, key, {
|
Object.defineProperty(refs, key, {
|
||||||
enumerable: true,
|
enumerable: true,
|
||||||
|
|
Loading…
Reference in New Issue