-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.ts
34 lines (30 loc) · 819 Bytes
/
index.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
import type { Component, Ref } from 'vue-demi'
import { customRef, getCurrentInstance, onUpdated } from 'vue-demi'
import { tryOnMounted } from '@vueuse/shared'
/**
* Shorthand for binding ref to template element.
*
* @see https://vueuse.org/templateRef
* @param key
* @param initialValue
*/
export function templateRef<T extends HTMLElement | SVGElement | Component | null>(
key: string,
initialValue: T | null = null,
): Readonly<Ref<T>> {
const instance = getCurrentInstance()
let _trigger = () => {}
const element = customRef((track, trigger) => {
_trigger = trigger
return {
get() {
track()
return instance?.proxy?.$refs[key] ?? initialValue
},
set() {},
}
})
tryOnMounted(_trigger)
onUpdated(_trigger)
return element as Readonly<Ref<T>>
}