Skip to content

useIntersectionObserver

类别
导出体积
638 B
上次更改
1 hour ago

检测目标元素的可见性。

示例

向下滚动我!

Hello world!

元素 外部 视口

使用方法

vue
<script setup lang="ts">
import { 
useIntersectionObserver
} from '@vueuse/core'
import {
shallowRef
,
useTemplateRef
} from 'vue'
const
target
=
useTemplateRef
<HTMLDivElement>('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>

指令使用

vue
<script setup lang="ts">
import { 
vIntersectionObserver
} from '@vueuse/components'
import {
shallowRef
,
useTemplateRef
} from 'vue'
const
root
=
useTemplateRef
<HTMLDivElement>('root')
const
isVisible
=
shallowRef
(false)
function
onIntersectionObserver
([
entry
]: IntersectionObserverEntry[]) {
isVisible
.
value
=
entry
?.
isIntersecting
|| false
} </script> <template> <
div
>
<
p
>
向下滚动! </
p
>
<
div
v-intersection-observ
er="
onIntersectionObserver
">
<
p
>Hello world!</
p
>
</
div
>
</
div
>
<!-- 使用选项 --> <
div
ref
="
root
">
<
p
>
向下滚动! </
p
>
<
div
v-intersection-observ
er="
[
onIntersectionObserver
, {
root
}]
">
<
p
>Hello world!</
p
>
</
div
>
</
div
>
</template>

IntersectionObserver MDN

类型声明

ts
export interface UseIntersectionObserverOptions extends ConfigurableWindow {
  /**
   * 在创建时立即启动 IntersectionObserver
   *
   * @default true
   */
  
immediate
?: boolean
/** * 用作边界框的元素或文档,用于测试相交时使用的边界框。 */
root
?:
MaybeComputedElementRef
| Document
/** * 一个字符串,指定计算相交时要添加到根边界框的偏移量集。 */
rootMargin
?: string
/** * 单个数字或介于 0.0 和 1 之间的数字数组。 * @default 0 */
threshold
?: number | number[]
} export interface UseIntersectionObserverReturn extends Pausable {
isSupported
:
ComputedRef
<boolean>
stop
: () => void
} /** * 检测目标元素的可见性。 * * @see https://vueuse.org/useIntersectionObserver * @param target * @param callback * @param options */ export declare function
useIntersectionObserver
(
target
:
|
MaybeComputedElementRef
|
MaybeRefOrGetter
<
MaybeElement
[]>
|
MaybeComputedElementRef
[],
callback
: IntersectionObserverCallback,
options
?: UseIntersectionObserverOptions,
): UseIntersectionObserverReturn

源码

源码演示文档

贡献者

一纸忘忧

更新日志

没有最近的更新日志