mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-08-26 05:39:45 +08:00
29 lines
627 B
TypeScript
29 lines
627 B
TypeScript
import { Ref, unref } from 'vue';
|
|
import { inBrowser } from '../shared';
|
|
import { 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 });
|
|
}
|