Skip to content

Commit

Permalink
Merge branch 'feat-useEventRef'
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 19, 2020
2 parents e3da226 + 7f20514 commit 66477dd
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 7 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export * from './useResize'
export * from './useScroll'
export * from './useScrollRef'
export * from './useWindowScroll'
export * from './useEventRef'
14 changes: 7 additions & 7 deletions src/useEvent.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
/* eslint-disable no-redeclare */
import { Ref, onMounted, onUnmounted, isRef, getCurrentInstance, shallowRef } from 'vue'

export type Target = Ref<EventTarget> | EventTarget | string
export type Target = Ref<EventTarget | null> | EventTarget | string

interface WindowEventHandler<T extends keyof WindowEventMap> {
export interface WindowEventHandler<T extends keyof WindowEventMap> {
(this: Window, e: WindowEventMap[T]): any
}

interface DocumentEventHandler<T extends keyof DocumentEventMap> {
export interface DocumentEventHandler<T extends keyof DocumentEventMap> {
(this: Document, e: DocumentEventMap[T]): any
}

type HandlerOptions = boolean | AddEventListenerOptions
type DocumentEvents = keyof DocumentEventMap
type WindowEvents = keyof WindowEventMap
export type HandlerOptions = boolean | AddEventListenerOptions
export type DocumentEvents = keyof DocumentEventMap
export type WindowEvents = keyof WindowEventMap

function getTarget(target: Target): EventTarget {
if (!target) {
Expand All @@ -28,7 +28,7 @@ function getTarget(target: Target): EventTarget {
return dom!
}
if (isRef(target)) {
return target.value
return target.value!
}
return target
}
Expand Down
12 changes: 12 additions & 0 deletions src/useEventRef.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ref, Ref } from 'vue'
import { useEvent, DocumentEventHandler, DocumentEvents, HandlerOptions } from './useEvent'

export function useEventRef<T extends DocumentEvents>(
event: T,
handler: DocumentEventHandler<T>,
options?: HandlerOptions
): Ref<Element | null> {
const target: Ref<Element | null> = ref(null)
useEvent(event, handler, options, target)
return target
}

0 comments on commit 66477dd

Please sign in to comment.