dx(useTemplateRef): warn when declaring with the same key (#11462)

This commit is contained in:
Tycho 2024-08-02 13:18:58 +08:00 committed by GitHub
parent 6d4eb94853
commit 55acabe88c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 5 deletions

View File

@ -68,4 +68,18 @@ describe('useTemplateRef', () => {
expect(t2!.value).toBe(root.children[0]) expect(t2!.value).toBe(root.children[0])
expect(t1!.value).toBe(null) expect(t1!.value).toBe(null)
}) })
test('should warn on duplicate useTemplateRef', () => {
const root = nodeOps.createElement('div')
render(
h(() => {
useTemplateRef('foo')
useTemplateRef('foo')
return ''
}),
root,
)
expect(`useTemplateRef('foo') already exists.`).toHaveBeenWarned()
})
}) })

View File

@ -10,11 +10,21 @@ export function useTemplateRef<T = unknown, Keys extends string = string>(
const r = shallowRef(null) const r = shallowRef(null)
if (i) { if (i) {
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
Object.defineProperty(refs, key, {
enumerable: true, let desc: PropertyDescriptor | undefined
get: () => r.value, if (
set: val => (r.value = val), __DEV__ &&
}) (desc = Object.getOwnPropertyDescriptor(refs, key)) &&
!desc.configurable
) {
warn(`useTemplateRef('${key}') already exists.`)
} else {
Object.defineProperty(refs, key, {
enumerable: true,
get: () => r.value,
set: val => (r.value = val),
})
}
} else if (__DEV__) { } else if (__DEV__) {
warn( warn(
`useTemplateRef() is called when there is no active component ` + `useTemplateRef() is called when there is no active component ` +