2024-07-17 18:20:23 +08:00
|
|
|
import { type ShallowRef, readonly, shallowRef } from '@vue/reactivity'
|
2024-07-19 10:50:06 +08:00
|
|
|
import { getCurrentInstance } from '../component'
|
|
|
|
import { warn } from '../warning'
|
2024-07-17 18:20:23 +08:00
|
|
|
import { EMPTY_OBJ } from '@vue/shared'
|
|
|
|
|
2024-08-01 11:13:56 +08:00
|
|
|
export function useTemplateRef<T = unknown, Keys extends string = string>(
|
|
|
|
key: Keys,
|
2024-07-17 18:20:23 +08:00
|
|
|
): Readonly<ShallowRef<T | null>> {
|
|
|
|
const i = getCurrentInstance()
|
|
|
|
const r = shallowRef(null)
|
|
|
|
if (i) {
|
|
|
|
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
|
2024-08-02 13:18:58 +08:00
|
|
|
|
|
|
|
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),
|
|
|
|
})
|
|
|
|
}
|
2024-07-17 18:20:23 +08:00
|
|
|
} else if (__DEV__) {
|
|
|
|
warn(
|
|
|
|
`useTemplateRef() is called when there is no active component ` +
|
|
|
|
`instance to be associated with.`,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
return (__DEV__ ? readonly(r) : r) as any
|
|
|
|
}
|