useElementVisibility
跟踪元素在视口内的可见性。
示例
用法
vue
<script setup lang="ts">
import { useElementVisibility } from '@vueuse/core'
import { useTemplateRef } from 'vue'
const target = useTemplateRef<HTMLDivElement>('target')
const targetIsVisible = useElementVisibility(target)
</script>
<template>
<div ref="target">
<h1>Hello world</h1>
</div>
</template>
rootMargin
如果你想在元素完全可见之前更早地触发回调,可以使用 rootMargin
选项(参见 MDN IntersectionObserver/rootMargin)。
ts
const targetIsVisible = useElementVisibility(target, {
rootMargin: '0px 0px 100px 0px',
})
组件用法
vue
<template>
<UseElementVisibility v-slot="{ isVisible }">
是否可见:{{ isVisible }}
</UseElementVisibility>
</template>
指令用法
vue
<script setup lang="ts">
import { vElementVisibility } from '@vueuse/components'
import { shallowRef, useTemplateRef } from 'vue'
const target = useTemplateRef<HTMLDivElement>('target')
const isVisible = shallowRef(false)
function onElementVisibility(state) {
isVisible.value = state
}
</script>
<template>
<div v-element-visibility="onElementVisibility">
{{ isVisible ? '在内部' : '在外部' }}
</div>
<!-- 使用选项 -->
<div ref="target">
<div v-element-visibility="[onElementVisibility, { scrollTarget: target }]">
{{ isVisible ? '在内部' : '在外部' }}
</div>
</div>
</template>
类型声明
typescript
export interface UseElementVisibilityOptions
extends ConfigurableWindow,
Pick<UseIntersectionObserverOptions, "threshold"> {
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/rootMargin
*/
rootMargin?: MaybeRefOrGetter<string>
/**
* The element that is used as the viewport for checking visibility of the target.
*/
scrollTarget?: MaybeRefOrGetter<HTMLElement | undefined | null>
/**
* Stop tracking when element visibility changes for the first time
*
* @default false
*/
once?: boolean
}
/**
* 跟踪元素在视口中的可见性
*
* @see https://vueuse.org/useElementVisibility
*/
export declare function useElementVisibility(
element: MaybeComputedElementRef,
options?: UseElementVisibilityOptions,
): ShallowRef<boolean, boolean>
源码
贡献者
更新日志
v12.8.0
on 3/5/2025v12.6.0
on 2/14/2025v12.3.0
on 1/2/202559f75
- feat(toValue): deprecate toValue
from @vueuse/shared
in favor of Vue's nativev12.1.0
on 12/22/2024v12.0.0-beta.1
on 11/21/2024v10.8.0
on 2/20/2024v10.7.0
on 12/5/2023v10.4.0
on 8/25/2023v10.0.0-beta.4
on 4/13/20234d757
- feat(types)!: rename MaybeComputedRef
to MaybeRefOrGetter
v10.0.0-beta.2
on 3/28/2023