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