通过 Vue Vueuse库的useElementVisibility 判断元素是否可见

通过 Vue Vueuse库的useElementVisibility判断元素是否可见,返回响应式对象。

代码示例

<template> 
   <div ref="el">
    目标元素是否可见:{{ targetIsVisible }}
   </div> 
</template>
<script setup lang="ts"> 
  import { ref } from 'vue'
  import { useElementVisibility  } from '@vueuse/core'
  //元素对象
  const el = ref(null);
  //元素是否可见
  const targetIsVisible  = useElementVisibility (el);
</script>

在线例子

例子

组件示例

也可以通过UseElementVisibility组件获取元素大小

<template>
<UseElementVisibility v-slot="{ isVisible }">
  是否可见: {{ isVisible }}
</UseElementVisibility>
</template>
<script setup>  
 //导入组件
 import {UseElementVisibility } from '@vueuse/components'
</script>

指令示例

也可以通过Vue 指令获取元素大小

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

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>

  <!-- 或者指定滚动条 -->
  <div ref="target">
    <div v-element-visibility="[onElementVisibility, { scrollTarget: target }]">
      {{ isVisible ? 'inside' : 'outside' }}
    </div>
  </div>
</template>

类型声明

export interface UseElementVisibilityOptions extends ConfigurableWindow {
  scrollTarget?: MaybeRefOrGetter<HTMLElement | undefined | null>
}
/**
 * Tracks the visibility of an element within the viewport.
 *
 * @see https://www.itxst.com/vueuse/tutorial.html
 * @param element
 * @param options
 */
export declare function useElementVisibility(
  element: MaybeComputedElementRef,
  { window, scrollTarget }?: UseElementVisibilityOptions
): Ref<boolean>