element-plus/packages/hooks/use-forward-ref/index.ts

39 lines
790 B
TypeScript
Raw Normal View History

import { provide } from 'vue'
2022-05-30 09:26:14 +08:00
import type { InjectionKey, ObjectDirective, Ref } from 'vue'
type ForwardRefSetter = <T>(el: T) => void
export type ForwardRefInjectionContext = {
setForwardRef: ForwardRefSetter
}
export const FORWARD_REF_INJECTION_KEY: InjectionKey<ForwardRefInjectionContext> =
Symbol('elForwardRef')
export const useForwardRef = <T>(forwardRef: Ref<T | null>) => {
const setForwardRef = (el: T) => {
forwardRef.value = el
}
provide(FORWARD_REF_INJECTION_KEY, {
setForwardRef,
})
}
2022-05-30 09:26:14 +08:00
export const useForwardRefDirective = (
setForwardRef: ForwardRefSetter
): ObjectDirective => {
return {
mounted(el) {
setForwardRef(el)
},
updated(el) {
setForwardRef(el)
},
unmounted() {
setForwardRef(null)
},
}
}