Created
May 8, 2022 15:22
-
-
Save jeongtae/056441335e24755ac629b51628655d28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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