Skip to content

useIntersectionObserver

类别
导出大小
646 B
最近修改
7 months ago

检测目标元素可见性的变化。

🌐 Detects changes to a target element's visibility.

示例

RootMargin: 0px 0px 0px 0px

Scroll me down!

Hello world!

Element outside the viewport

用法

🌐 Usage

vue
<script setup lang="ts">
import { 
useIntersectionObserver
} from '@vueuse/core'
import {
shallowRef
,
useTemplateRef
} from 'vue'
const
target
=
useTemplateRef
('target')
const
targetIsVisible
=
shallowRef
(false)
const {
stop
} =
useIntersectionObserver
(
target
,
([
entry
],
observerElement
) => {
targetIsVisible
.
value
=
entry
?.
isIntersecting
|| false
}, ) </script> <template> <
div
ref
="
target
">
<
h1
>Hello world</
h1
>
</
div
>
</template>

控制和清理

🌐 Controls and cleanup

useIntersectionObserver 返回底层观察者的控制项:

状态类型描述
isSupportedComputedRef<boolean>IntersectionObserver API 是否可用。
isActiveShallowRef<boolean>观察者当前是否正在运行。在 pause()stop() 后会变成 false
pause() => void暂停观察,并将 isActive 设置为 false
resume() => void恢复观察。
stop() => void永久停止观察。

当创建它的组件或 effect 范围被销毁时,观察者会通过 tryOnScopeDispose 自动断开,所以在大多数情况下你不需要自己调用 stop。例如,当元素变为可见时,可以调用 stop() 提前断开观察者:

🌐 The observer is disconnected automatically via tryOnScopeDispose when the component or effect scope that created it is disposed, so in most cases you don't need to call stop yourself. Call stop() to disconnect the observer earlier, for example once the element has become visible:

ts
const { 
stop
} =
useIntersectionObserver
(
target, ([
entry
]) => {
if (
entry
?.
isIntersecting
) {
// react to the element becoming visible once, then stop observing
stop
()
} }, )
js
'use strict'
const { stop } = useIntersectionObserver(target, ([entry]) => {
  if (entry?.isIntersecting) {
    // react to the element becoming visible once, then stop observing
    stop()
  }
})

指令用法

🌐 Directive Usage

vue
<script setup lang="ts">
import { 
vIntersectionObserver
} from '@vueuse/components'
import {
shallowRef
,
useTemplateRef
} from 'vue'
const
root
=
useTemplateRef
('root')
const
isVisible
=
shallowRef
(false)
function
onIntersectionObserver
([
entry
]: IntersectionObserverEntry[]) {
isVisible
.
value
=
entry
?.
isIntersecting
|| false
} </script> <template> <
div
>
<
p
>
Scroll me down! </
p
>
<
div
v-intersection-observ
er="
onIntersectionObserver
">
<
p
>Hello world!</
p
>
</
div
>
</
div
>
<!-- with options --> <
div
ref
="
root
">
<
p
>
Scroll me down! </
p
>
<
div
v-intersection-observ
er="
[
onIntersectionObserver
, {
root
}]
">
<
p
>Hello world!</
p
>
</
div
>
</
div
>
</template>

IntersectionObserver MDN