Vueuse useIntersectionObserver 检测元素是否可见,与useElementVisibility不同的是你可停止检测行为。
<script setup lang="ts">
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
//需要检测元素
const target = ref(null)
//被监测对象是否可见
const isVisible = ref(false)
//isActive 是否可用, pause 暂停检测, resume 重置事件
const { isActive, pause, resume } = useIntersectionObserver(
target,
([{ isIntersecting }]) => {
isVisible.value = isIntersecting
},
{ root },
)
</script>
<template>
<div ref="target">
www.itxst.com
</div>
</template>
例子
也可以通过Vue指令获取元素是否可见
<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>
向下滚动试试看!
</p>
<!-- 默认的例子 -->
<div v-intersection-observer="onIntersectionObserver">
<p>Hello world!</p>
</div>
</div>
<!-- 指定对象的例子 -->
<div ref="root">
<p>
向下滚动试试看!
</p>
<div v-intersection-observer="[onIntersectionObserver, { root }]">
<p>Hello world!</p>
</div>
</div>
</template>
export interface UseIntersectionObserverOptions extends ConfigurableWindow {
/**
* 创建时立即启动IntersectionObserver
*
* 默认: true
*/
immediate?: boolean
/**
* 在测试交集时,其边界用作边界框的元素或文档。
*/
root?: MaybeComputedElementRef
/**
* A string which specifies a set of offsets to add to the root's bounding_box when calculating intersections.
*/
rootMargin?: string
/**
* 介于0.0和1之间的数字。
*/
threshold?: number | number[]
}
export interface UseIntersectionObserverReturn extends Pausable {
isSupported: Ref<boolean>
stop: () => void
}
/**
* Detects that a target element's visibility.
*
* @see https://www.itxst.com/vueuse/tutorial.html
* @param target
* @param callback
* @param options
*/
export declare function useIntersectionObserver(
target:
| MaybeComputedElementRef
| MaybeRefOrGetter<MaybeElement[]>
| MaybeComputedElementRef[],
callback: IntersectionObserverCallback,
options?: UseIntersectionObserverOptions
): UseIntersectionObserverReturn