chore: minor tweaks

This commit is contained in:
daiwei 2025-02-17 18:10:12 +08:00
parent 5b53f8e209
commit 044b4d8a9a
2 changed files with 8 additions and 4 deletions

View File

@ -70,19 +70,22 @@ describe('useTemplateRef', () => {
expect(t1!.value).toBe(null)
})
test('should warn and return same value 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(() => {
f1 = useTemplateRef('foo')
f2 = useTemplateRef('foo')
return ''
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)
})

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'
@ -20,6 +20,7 @@ export function useTemplateRef<T = unknown, Keys extends string = string>(
if (__DEV__) {
warn(`useTemplateRef('${key}') already exists.`)
}
return toRef(() => refs[key]) as unknown as Readonly<ShallowRef<T>>
} else {
Object.defineProperty(refs, key, {
enumerable: true,