useWindowSizeFn.ts 886 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { type AnyFunction } from '@vben/types';
  2. import { tryOnMounted, tryOnUnmounted, useDebounceFn } from '@vueuse/core';
  3. interface UseWindowSizeOptions {
  4. wait?: number;
  5. once?: boolean;
  6. immediate?: boolean;
  7. listenerOptions?: AddEventListenerOptions | boolean;
  8. }
  9. function useWindowSizeFn(fn: AnyFunction, options: UseWindowSizeOptions = {}) {
  10. const { wait = 150, immediate } = options;
  11. let handler = () => {
  12. fn();
  13. };
  14. const handleSize = useDebounceFn(handler, wait);
  15. handler = handleSize;
  16. const start = () => {
  17. if (immediate) {
  18. handler();
  19. }
  20. window.addEventListener('resize', handler);
  21. };
  22. const stop = () => {
  23. window.removeEventListener('resize', handler);
  24. };
  25. tryOnMounted(() => {
  26. start();
  27. });
  28. tryOnUnmounted(() => {
  29. stop();
  30. });
  31. return { start, stop };
  32. }
  33. export { useWindowSizeFn, type UseWindowSizeOptions };