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

38 lines
816 B
TypeScript
Raw Normal View History

2021-03-10 22:23:19 +08:00
import { tryOnMounted, tryOnUnmounted } from '@vueuse/core';
2020-09-28 20:19:10 +08:00
import { useDebounce } from '/@/hooks/core/useDebounce';
interface WindowSizeOptions {
once?: boolean;
immediate?: boolean;
listenerOptions?: AddEventListenerOptions | boolean;
}
2020-10-19 23:50:47 +08:00
export function useWindowSizeFn<T>(fn: Fn<T>, wait = 150, options?: WindowSizeOptions) {
2020-09-28 20:19:10 +08:00
let handler = () => {
fn();
};
const [handleSize, cancel] = useDebounce(handler, wait, options);
handler = handleSize;
2020-10-19 23:50:47 +08:00
const start = () => {
2020-10-19 22:56:10 +08:00
if (options && options.immediate) {
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);
cancel();
2020-10-19 23:50:47 +08:00
};
tryOnMounted(() => {
start();
});
tryOnUnmounted(() => {
stop();
2020-09-28 20:19:10 +08:00
});
2020-10-19 23:50:47 +08:00
return [start, stop];
2020-09-28 20:19:10 +08:00
}