vue-vben-admin/packages/hooks/src/useWindowSizeFn.ts

41 lines
886 B
TypeScript
Raw Normal View History

import { type AnyFunction } from '@vben/types';
import { tryOnMounted, tryOnUnmounted, useDebounceFn } from '@vueuse/core';
2020-09-28 20:19:10 +08:00
interface UseWindowSizeOptions {
wait?: number;
2020-09-28 20:19:10 +08:00
once?: boolean;
immediate?: boolean;
listenerOptions?: AddEventListenerOptions | boolean;
}
function useWindowSizeFn(fn: AnyFunction, options: UseWindowSizeOptions = {}) {
const { wait = 150, immediate } = options;
2020-09-28 20:19:10 +08:00
let handler = () => {
fn();
};
2021-04-10 20:32:44 +08:00
const handleSize = useDebounceFn(handler, wait);
2020-09-28 20:19:10 +08:00
handler = handleSize;
2020-10-19 23:50:47 +08:00
const start = () => {
if (immediate) {
2020-10-19 22:56:10 +08:00
handler();
}
2020-09-28 20:19:10 +08:00
window.addEventListener('resize', handler);
2020-10-19 23:50:47 +08:00
};
2020-10-15 21:12:38 +08:00
2020-10-19 23:50:47 +08:00
const stop = () => {
2020-09-28 20:19:10 +08:00
window.removeEventListener('resize', handler);
2020-10-19 23:50:47 +08:00
};
tryOnMounted(() => {
start();
});
tryOnUnmounted(() => {
stop();
2020-09-28 20:19:10 +08:00
});
return { start, stop };
2020-09-28 20:19:10 +08:00
}
export { useWindowSizeFn, type UseWindowSizeOptions };