From 0d5b53d2a58930de0a1c8e70a8653220dff0a8d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=98=89=E6=B6=B5?= Date: Sat, 11 Jan 2020 21:13:54 +0800 Subject: [PATCH] feat: add use-handler hook --- src/hooks/use-handler.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/hooks/use-handler.ts diff --git a/src/hooks/use-handler.ts b/src/hooks/use-handler.ts new file mode 100644 index 000000000..8fb12d6cc --- /dev/null +++ b/src/hooks/use-handler.ts @@ -0,0 +1,30 @@ +import { on, off } from '../utils'; +import { onMounted, onActivated, onUnmounted, onDeactivated } from 'vue'; + +export function useHandler( + target: HTMLElement | Document | Window, + event: string, + handler: any, + passive = false +) { + let added: boolean; + + function add() { + if (!added) { + on(target, event, handler, passive); + added = true; + } + } + + function remove() { + if (added) { + off(target, event, handler); + added = false; + } + } + + onMounted(add); + onActivated(add); + onUnmounted(remove); + onDeactivated(remove); +}