vue3 VueUse useElementVisibility 来监听某一个元素或者div是否在当前视口viewport中可见。

1、先上一个图:

2、安装@vueuse/core

复制代码
pnpm add @vueuse/core

3、新建一个组件:

复制代码
<script setup lang="ts">
import { ref, watch } from "vue";
import { useElementVisibility } from "@vueuse/core";

const target = ref(null);
const targetIsVisible = useElementVisibility(target);
let emit = defineEmits(["showVisible"]);

watch(targetIsVisible, (newValue) => {
  if (newValue) {
    emit("showVisible",newValue);
  } else {
    emit("showVisible",newValue);
  }
});
</script>

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

这里面是利用@vueuse/core提供的useElementVisibility,来监听ref="target"的可见状态。然后我们用watch去监听这个属性的变化,然后汇报给App.vue。

4、引用刚建的组件到App.vue

这样我们就可以成功的去看这个div是不是在viewport可见范围了。

官网:

useElementVisibility | VueUse

相关推荐
FYKJ_20109 小时前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
FYKJ_201016 小时前
springboot贺州地方新闻网站87812-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·django·课程设计
何何____16 小时前
Vue 全局事件总线详解
前端·javascript·vue.js
EatFan17 小时前
Go语言全栈实战:基于 Gin + Vue + JWT + RBAC 从零搭建前后端分离权限管理系统
vue.js·golang·go·vue·gin·jwt·rbac
陈拉斯18 小时前
Vue SPA 站百度收录“全军覆没“?一次预渲染抢救的完整实战(2026 踩坑版)
vue.js
一 乐1 天前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
wengad1 天前
从 wangEditor 迁到 wangEditor-next
前端·javascript·vue.js
FYKJ_20101 天前
django电影推荐系统55066-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
qq_316837751 天前
阿里云百炼 fun-asr-realtime uniapp vue3 调用
javascript·vue.js·uni-app
李剑一1 天前
AntDesign老版本没有月份和年份区间选择组件?我封装了一个完美版,附源码!
前端·vue.js