mirror of
https://github.com/youzan/vant.git
synced 2025-10-19 01:54:48 +00:00
feat(use): add useClickAway
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
export { useToggle } from './useToggle';
|
||||
export { useClickAway } from './useClickAway';
|
||||
export { useEventListener } from './useEventListener';
|
||||
|
27
packages/vant-use/src/useClickAway/index.ts
Normal file
27
packages/vant-use/src/useClickAway/index.ts
Normal 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 });
|
||||
}
|
@@ -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;
|
||||
|
Reference in New Issue
Block a user