useIntersectionObserver.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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({
  10. target,
  11. root,
  12. onIntersect,
  13. rootMargin = '0px',
  14. threshold = 0.1,
  15. }: IntersectionObserverProps) {
  16. let cleanup = () => {};
  17. const observer: Ref<Nullable<IntersectionObserver>> = ref(null);
  18. const stopEffect = watchEffect(() => {
  19. cleanup();
  20. observer.value = new IntersectionObserver(onIntersect, {
  21. root: root ? root.value : null,
  22. rootMargin,
  23. threshold,
  24. });
  25. const current = target.value;
  26. current && observer.value.observe(current);
  27. cleanup = () => {
  28. if (observer.value) {
  29. observer.value.disconnect();
  30. target.value && observer.value.unobserve(target.value);
  31. }
  32. };
  33. });
  34. return {
  35. observer,
  36. stop: () => {
  37. cleanup();
  38. stopEffect();
  39. },
  40. };
  41. }