useIntersectionObserver
Detects that a target element's visibility.
Demo
Usage
html
<div ref="target">
<h1>Hello world</h1>
</div>
<div ref="target">
<h1>Hello world</h1>
</div>
js
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
)
return {
target,
targetIsVisible,
}
},
}
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
export default {
setup() {
const target = ref(null)
const targetIsVisible = ref(false)
const { stop } = useIntersectionObserver(
target,
([{ isIntersecting }], observerElement) => {
targetIsVisible.value = isIntersecting
},
)
return {
target,
targetIsVisible,
}
},
}
Directive Usage
This function also provides a directive version via the
@vueuse/components
package. Learn more about the usage.
html
<script setup lang="ts">
import { ref } from 'vue'
import { vIntersectionObserver } from '@vueuse/components'
const root = ref(null)
const isVisible = ref(false)
function onIntersectionObserver([{ isIntersecting }]) {
isVisible.value = isIntersecting
}
</script>
<template>
<div>
<p>
Scroll me down!
</p>
<div v-intersection-observer="onIntersectionObserver">
<p>Hello world!</p>
</div>
</div>
<!-- with options -->
<div ref="root">
<p>
Scroll me down!
</p>
<div v-intersection-observer="[onIntersectionObserver, { root }]">
<p>Hello world!</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { vIntersectionObserver } from '@vueuse/components'
const root = ref(null)
const isVisible = ref(false)
function onIntersectionObserver([{ isIntersecting }]) {
isVisible.value = isIntersecting
}
</script>
<template>
<div>
<p>
Scroll me down!
</p>
<div v-intersection-observer="onIntersectionObserver">
<p>Hello world!</p>
</div>
</div>
<!-- with options -->
<div ref="root">
<p>
Scroll me down!
</p>
<div v-intersection-observer="[onIntersectionObserver, { root }]">
<p>Hello world!</p>
</div>
</div>
</template>
Source
Contributors
Changelog
v10.0.2
on 4/14/2023v10.0.1
on 4/14/2023v10.0.0
on 4/14/2023v10.0.0-beta.4
on 4/13/2023v10.0.0-beta.2
on 3/28/202374b00
- fix(useElementVisibility)!: use useIntersectionObserver instead of scroll event handler (#2551)v8.9.3
on 7/14/2022v8.9.2
on 7/12/2022