feat(use): add useClickAway

This commit is contained in:
chenjiahan
2020-09-12 21:29:08 +08:00
parent a58da5570b
commit 195f3ffea1
8 changed files with 37 additions and 92 deletions
@@ -0,0 +1,27 @@
import { Ref, unref } from 'vue';
import { inBrowser, useEventListener } from '../useEventListener';
export type UseClickAwayOptions = {
eventName?: string;
};
export function useClickAway(
target: Element | Ref<Element>,
listener: EventListener,
options: UseClickAwayOptions = {}
) {
if (!inBrowser) {
return;
}
const { eventName = 'click' } = options;
const onClick = (event: Event) => {
const element = unref(target);
if (!element.contains(event.target as Node)) {
listener(event);
}
};
useEventListener(eventName, onClick, { target: document });
}