refactor(use): adjust useEventListener params

This commit is contained in:
chenjiahan 2020-09-12 21:16:44 +08:00
parent 9b502bcbbd
commit a58da5570b
5 changed files with 24 additions and 36 deletions

View File

@ -24,26 +24,28 @@ if (inBrowser) {
}
export type UseEventListenerOptions = {
type: string;
target: EventTarget | Ref<EventTarget>;
target?: EventTarget | Ref<EventTarget>;
capture?: boolean;
passive?: boolean;
listener: EventListener;
};
export function useEventListener({
type,
target,
passive = false,
capture = false,
listener,
}: UseEventListenerOptions) {
export function useEventListener(
type: string,
listener: EventListener,
options: UseEventListenerOptions
) {
if (!inBrowser) {
return;
}
const { target = window, passive = false, capture = false } = options;
let attached: boolean;
const add = () => {
const element = unref(target);
if (element && inBrowser && !attached) {
if (element && !attached) {
element.addEventListener(
type,
listener,
@ -56,7 +58,7 @@ export function useEventListener({
const remove = () => {
const element = unref(target);
if (element && inBrowser && attached) {
if (element && attached) {
element.removeEventListener(type, listener, capture);
attached = false;
}

View File

@ -72,6 +72,12 @@ export default createComponent({
}
};
const onScroll = () => {
if (opened.value) {
updateOffset();
}
};
const toggleItem = (active) => {
children.forEach((item, index) => {
if (index === active) {
@ -121,15 +127,7 @@ export default createComponent({
callback: onClickOutside,
});
useEventListener({
type: 'scroll',
target: scroller,
listener() {
if (opened.value) {
updateOffset();
}
},
});
useEventListener('scroll', onScroll, { target: scroller });
return () => (
<div ref={rootRef} class={bem()}>

View File

@ -156,11 +156,7 @@ export default createComponent({
}
};
useEventListener({
type: 'scroll',
target: scroller,
listener: onScroll,
});
useEventListener('scroll', onScroll, { target: scroller });
watch(
() => props.indexList,

View File

@ -143,11 +143,7 @@ export default createComponent({
usePublicApi({ check });
useEventListener({
type: 'scroll',
target: scroller,
listener: check,
});
useEventListener('scroll', check, { target: scroller });
return () => {
const Content = slots.default?.();

View File

@ -101,11 +101,7 @@ export default createComponent({
emitScrollEvent(scrollTop);
};
useEventListener({
type: 'scroll',
target: scroller,
listener: onScroll,
});
useEventListener('scroll', onScroll, { target: scroller });
useVisibilityChange(rootRef, onScroll);