29 lines
650 B
TypeScript
29 lines
650 B
TypeScript
import { onMounted, onUnmounted, ref, type Ref } from 'vue'
|
|
|
|
export function useIntersection(
|
|
target: Ref<Element | null | undefined>,
|
|
options?: IntersectionObserverInit,
|
|
): {
|
|
isVisible: Ref<boolean>
|
|
} {
|
|
const isVisible = ref(false)
|
|
let observer: IntersectionObserver | null = null
|
|
|
|
onMounted(() => {
|
|
const el = target.value
|
|
if (!el) return
|
|
observer = new IntersectionObserver((entries) => {
|
|
const entry = entries[0]
|
|
if (entry) isVisible.value = entry.isIntersecting
|
|
}, options)
|
|
observer.observe(el)
|
|
})
|
|
|
|
onUnmounted(() => {
|
|
observer?.disconnect()
|
|
observer = null
|
|
})
|
|
|
|
return { isVisible }
|
|
}
|