-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
Copy pathuseTemplateRef.ts
42 lines (39 loc) · 1.2 KB
/
useTemplateRef.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { type ShallowRef, readonly, shallowRef } from '@vue/reactivity'
import { getCurrentInstance } from '../component'
import { warn } from '../warning'
import { EMPTY_OBJ } from '@vue/shared'
export const knownTemplateRefs: WeakSet<ShallowRef> = new WeakSet()
export type TemplateRef<T = unknown> = Readonly<ShallowRef<T | null>>
export function useTemplateRef<T = unknown, Keys extends string = string>(
key: Keys,
): TemplateRef<T> {
const i = getCurrentInstance()
const r = shallowRef(null)
if (i) {
const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs
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 ` +
`instance to be associated with.`,
)
}
const ret = __DEV__ ? readonly(r) : r
if (__DEV__) {
knownTemplateRefs.add(ret)
}
return ret
}