Skip to content

useElementVisibility

跟踪视口中元素的可见性。

¥Tracks the visibility of an element within the viewport.

示例

Info on the right bottom corner
Target Element (scroll down)
Element outside the viewport

用法

¥Usage

vue
<script setup>
import { useElementVisibility } from '@vueuse/core'
import { ref } from 'vue'

const target = ref(null)
const targetIsVisible = useElementVisibility(target)
</script>

<template>
  <div ref="target">
    <h1>Hello world</h1>
  </div>
</template>

rootMargin

如果你希望在元素完全可见之前尽早触发回调,则可以使用 rootMargin 选项(参见 MDN IntersectionObserver/rootMargin)。

¥If you wish to trigger your callback sooner before the element is fully visible, you can use the rootMargin option (See MDN IntersectionObserver/rootMargin).

ts
const targetIsVisible = useElementVisibility(target, {
  rootMargin: '0 0 100px 0',
})

组件用法

¥Component Usage

vue
<template>
  <UseElementVisibility v-slot="{ isVisible }">
    Is Visible: {{ isVisible }}
  </UseElementVisibility>
</template>

指令用法

¥Directive Usage

vue
<script setup>
import { vElementVisibility } from '@vueuse/components'
import { ref } from 'vue'

const target = ref(null)
const isVisible = ref(false)

function onElementVisibility(state) {
  isVisible.value = state
}
</script>

<template>
  <div v-element-visibility="onElementVisibility">
    {{ isVisible ? 'inside' : 'outside' }}
  </div>

  <!-- with options -->
  <div ref="target">
    <div v-element-visibility="[onElementVisibility, { scrollTarget: target }]">
      {{ isVisible ? 'inside' : 'outside' }}
    </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>
}
/**
 * Tracks the visibility of an element within the viewport.
 *
 * @see https://vueuse.org/useElementVisibility
 */
export declare function useElementVisibility(
  element: MaybeComputedElementRef,
  options?: UseElementVisibilityOptions,
): Ref<boolean, boolean>

源代码

源代码示例文档

变更日志

v12.3.0 on 1/2/2025
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
v12.1.0 on 12/22/2024
3a928 - feat: add rootMargin option (#4100)

VueUse 中文网 - 粤ICP备13048890号