Skip to content

Commit

Permalink
feat(useEventRef): add useEventRef
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 19, 2020
1 parent 9bc82da commit 7f20514
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './useTitle'
export * from './useEvent'
export * from './useEventRef'
12 changes: 6 additions & 6 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 } from 'vue'

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 | null {
if (!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 7f20514

Please sign in to comment.