useWindowSizeFn.ts 774 B

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