feat: add use-handler hook

This commit is contained in:
陈嘉涵 2020-01-11 21:13:54 +08:00
parent 6d4efa183e
commit 0d5b53d2a5

30
src/hooks/use-handler.ts Normal file
View File

@ -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);
}