通过 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>