Skip to content

Commit

Permalink
dx(useTemplateRef): warn when declaring with the same key (#11462)
Browse files Browse the repository at this point in the history
  • Loading branch information
jh-leong authored Aug 2, 2024
1 parent 6d4eb94 commit 55acabe
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
14 changes: 14 additions & 0 deletions packages/runtime-core/__tests__/helpers/useTemplateRef.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,18 @@ describe('useTemplateRef', () => {
expect(t2!.value).toBe(root.children[0])
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()
})
})
20 changes: 15 additions & 5 deletions packages/runtime-core/src/helpers/useTemplateRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,21 @@ export function useTemplateRef<T = unknown, Keys extends string = string>(
const r = shallowRef(null)
if (i) {
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
Object.defineProperty(refs, key, {
enumerable: true,
get: () => r.value,
set: val => (r.value = val),
})

let desc: PropertyDescriptor | undefined
if (
__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__) {
warn(
`useTemplateRef() is called when there is no active component ` +
Expand Down

0 comments on commit 55acabe

Please sign in to comment.