mirror of
https://gitee.com/vant-contrib/vant.git
synced 2025-04-05 19:41:42 +08:00
feat(use): add useEventListener
This commit is contained in:
parent
df0a055ce6
commit
977b14cce8
@ -1 +1,2 @@
|
||||
export { useToggle } from './useToggle';
|
||||
export { useEventListener } from './useEventListener';
|
||||
|
69
packages/vant-use/src/useEventListener/index.ts
Normal file
69
packages/vant-use/src/useEventListener/index.ts
Normal file
@ -0,0 +1,69 @@
|
||||
import {
|
||||
Ref,
|
||||
unref,
|
||||
onMounted,
|
||||
onActivated,
|
||||
onUnmounted,
|
||||
onDeactivated,
|
||||
} from 'vue';
|
||||
|
||||
const inBrowser = typeof window !== 'undefined';
|
||||
|
||||
let supportsPassive = false;
|
||||
if (inBrowser) {
|
||||
try {
|
||||
const opts = {};
|
||||
Object.defineProperty(opts, 'passive', {
|
||||
get() {
|
||||
supportsPassive = true;
|
||||
},
|
||||
});
|
||||
window.addEventListener('test-passive', null as any, opts);
|
||||
// eslint-disable-next-line no-empty
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
export type UseEventListenerOptions = {
|
||||
type: string;
|
||||
target: EventTarget | Ref<EventTarget>;
|
||||
capture?: boolean;
|
||||
passive?: boolean;
|
||||
listener: EventListener;
|
||||
};
|
||||
|
||||
export function useEventListener({
|
||||
type,
|
||||
target,
|
||||
passive = false,
|
||||
capture = false,
|
||||
listener,
|
||||
}: UseEventListenerOptions) {
|
||||
let attached: boolean;
|
||||
|
||||
const add = () => {
|
||||
const element = unref(target);
|
||||
|
||||
if (element && inBrowser && !attached) {
|
||||
element.addEventListener(
|
||||
type,
|
||||
listener,
|
||||
supportsPassive ? { capture, passive } : capture
|
||||
);
|
||||
attached = true;
|
||||
}
|
||||
};
|
||||
|
||||
const remove = () => {
|
||||
const element = unref(target);
|
||||
|
||||
if (element && inBrowser && attached) {
|
||||
element.removeEventListener(type, listener, capture);
|
||||
attached = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(add);
|
||||
onActivated(add);
|
||||
onUnmounted(remove);
|
||||
onDeactivated(remove);
|
||||
}
|
@ -7,8 +7,7 @@
|
||||
"declaration": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"moduleResolution": "Node",
|
||||
"lib": ["esnext"]
|
||||
"moduleResolution": "Node"
|
||||
},
|
||||
"include": ["src/**/*"]
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user