# t-visibility-sensor
VisibilitySensor 可见性传感器
t-visibility-sensor 组件介绍
t-visibility-sensor 是用于监听元素是否在可视区域内的组件,当元素进入或离开视口时会触发相应事件,适用于懒加载、埋点统计、动画触发等场景。
t-visibility-sensor 平台兼容
| Harmony | H5 | Android | iOS | 小程序 | UTS |
|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
t-visibility-sensor 基础用法
基础用法参考 demo/visibility-sensor/visibility-sensor.uvue。
vue
<template>
<t-page class="p-15 b"
@scroll="onscroll">
<tui-theme-switch></tui-theme-switch>
<t-card title="VisibilitySensor"
class="mb-15"
sub-title="监听元素是否在可视区"></t-card>
<t-button type="primary"
class="df db-75 dlr-15 z-1">{{showText}}</t-button>
<t-row class="h-150 r-10 mb-15"></t-row>
<t-visibility-sensor @change="vischange"
mark="图片1"
:scrollTop="scrollTop">
<t-col class="w-100%">
<t-image class="h-150 r-10 mb-15 w-100%"
src='/static/image/D2.jpg'></t-image>
</t-col>
</t-visibility-sensor>
<t-row class="h-150 r-10 mb-15"></t-row>
<t-row class="h-400 r-10 mb-15"></t-row>
<t-visibility-sensor @change="vischange"
mark="图片2"
:scrollTop="scrollTop">
<t-col class="w-100%">
<t-image class="h-150 r-10 mb-15 w-100%"
src='/static/image/D2.jpg'></t-image>
</t-col>
</t-visibility-sensor>
<t-row class="h-150 r-10 mb-15"></t-row>
<t-row class="h-150 r-10 mb-15"></t-row>
<t-row class="h-150 r-10 mb-15"></t-row>
</t-page>
</template>
<script setup>
import { ref } from 'vue'
const scrollTop = ref(0)
const showText = ref('')
function onscroll(e : ScrollEvent) {
console.log(e.detail.scrollTop)
scrollTop.value = e.detail.scrollTop
}
const vischange = (e : UTSJSONObject) => {
const state = e.getBoolean('state') ?? false
const mark = e.getString('mark')!
showText.value = mark + (state ? '可见' : '不可见')
}
</script>t-visibility-sensor Props
| 属性名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
scrollTop | 滚动组件的 scrollTop 值 | number | 0 |
mark | 组件标记,用于区分不同元素 | string | '' |
path | 点击组件后跳转的页面路径 | string | '' |
hover | 是否启用点击效果 | boolean | false |
type | 组件主题类型 | string | '' |
disabled | 是否禁用 | boolean | false |
effect | 组件显示主题 | string | 'plain' |
size | 组件尺寸 | string | '' |
t-visibility-sensor Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
visible | 元素可见性变化时触发 | boolean(是否可见) |
change | 元素状态发生变化时触发 | { ins: instance, state: boolean, mark: string } |
transitionend | 动画结束时触发 | event |
插槽
| 插槽名 | 说明 |
|---|---|
default | 需要监听可见性的内容 |