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

View File

@@ -1,2 +1,3 @@
export { useToggle } from './useToggle';
export { useClickAway } from './useClickAway';
export { useEventListener } from './useEventListener';

View File

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

View File

@@ -7,7 +7,7 @@ import {
onDeactivated,
} from 'vue';
const inBrowser = typeof window !== 'undefined';
export const inBrowser = typeof window !== 'undefined';
let supportsPassive = false;
if (inBrowser) {
@@ -32,7 +32,7 @@ export type UseEventListenerOptions = {
export function useEventListener(
type: string,
listener: EventListener,
options: UseEventListenerOptions
options: UseEventListenerOptions = {}
) {
if (!inBrowser) {
return;