useIntersectionObserver.ts 1020 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Ref, watchEffect, ref } from 'vue';
  2. interface IntersectionObserverProps {
  3. target: Ref<Element | null | undefined>;
  4. root?: Ref<any>;
  5. onIntersect: IntersectionObserverCallback;
  6. rootMargin?: string;
  7. threshold?: number;
  8. }
  9. export function useIntersectionObserver({ target, root, onIntersect, rootMargin = '0px', threshold = 0.1 }: IntersectionObserverProps) {
  10. let cleanup = () => {};
  11. const observer: Ref<Nullable<IntersectionObserver>> = ref(null);
  12. const stopEffect = watchEffect(() => {
  13. cleanup();
  14. observer.value = new IntersectionObserver(onIntersect, {
  15. root: root ? root.value : null,
  16. rootMargin,
  17. threshold,
  18. });
  19. const current = target.value;
  20. current && observer.value.observe(current);
  21. cleanup = () => {
  22. if (observer.value) {
  23. observer.value.disconnect();
  24. target.value && observer.value.unobserve(target.value);
  25. }
  26. };
  27. });
  28. return {
  29. observer,
  30. stop: () => {
  31. cleanup();
  32. stopEffect();
  33. },
  34. };
  35. }