Skip to content

Instantly share code, notes, and snippets.

@jeongtae
Created May 8, 2022 15:22
Show Gist options
  • Save jeongtae/056441335e24755ac629b51628655d28 to your computer and use it in GitHub Desktop.
Save jeongtae/056441335e24755ac629b51628655d28 to your computer and use it in GitHub Desktop.
import { onUnmounted, Ref, watch } from '@vue/composition-api';
export type UseIntersectionObserverEntry<E extends HTMLElement> =
IntersectionObserverEntry & { target: E };
export type UseIntersectionObserverCallback<E extends HTMLElement> = (
entry: UseIntersectionObserverEntry<E>,
) => void;
export const useIntersectionObserver = <E extends HTMLElement>(
elementRef: Ref<E | null>,
callback: UseIntersectionObserverCallback<E>,
// options?: IntersectionObserverInit,
) => {
const observer = new IntersectionObserver(([entry]) => {
if (entry) {
callback(entry as unknown as UseIntersectionObserverEntry<E>);
}
});
watch(elementRef, (nextElement, prevElement) => {
if (prevElement) {
observer.unobserve(prevElement);
}
if (nextElement) {
observer.observe(nextElement);
}
});
onUnmounted(() => {
observer.disconnect();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment