当前位置: 首页 > news >正文

vue3+ts:监听dom宽高变化函数

一、效果展示

二、代码

getSize.ts

import { ref, Ref, watchEffect } from "vue";export const getWidth = (domRef: Ref<HTMLElement | null>) => {const width = ref<number>(0);const height = ref<number>(0);const observer = new ResizeObserver(() => {if (domRef.value) {width.value = domRef.value.clientWidth;height.value = domRef.value.clientHeight;}console.log("width", width.value);});//设置一个变量来存储dom元素,让ResizeObserver知道它要监听哪个元素//因为domRef.value可能会变化,所以我们需要一个变量来存储它,这样我们就可以在domRef.value变化的时候取消监听,防止内存泄漏并提高性能//如果在该函数中需要同时监听多个dom,可以考虑使用weakMap来存储dom和ResizeObserver实例let observerDom: HTMLElement | null = null;watchEffect(() => {const newDom = domRef.value;//如果我们传入的dom存在,就让ResizeObserver监听它//如果我们传入的dom不存在,就让ResizeObserver取消监听if (newDom) {observerDom = newDom;observer.observe(observerDom);} else if (observerDom) {observer.unobserve(observerDom);}});return { width, height };
};

组件中使用:

<template><div class="page"><div class="observerDom" ref="observerRef">{{ width.width }}</div></div>
</template><script setup lang="ts">
import { ref } from "vue";
import { getWidth } from "./getSize";
const observerRef = ref();
const width = getWidth(observerRef);
</script>
<style scoped>
.page {width: 100%;height: 100vh;display: flex;justify-content: center;align-items: center;background-color: #8c4141;
}
.observerDom {width: 60%;height: 60px;background-color: #f1f1f1;
}
</style>

http://www.lryc.cn/news/383247.html

相关文章:

  • 数据库浅识及MySQL的二进制安装
  • 机器学习之数学基础(七)~过拟合(over-fitting)和欠拟合(under-fitting)
  • ⭐最新版!SpringBoot正确集成PageHelper姿势,不再被误导!
  • 解决:Xshell通过SSH协议连接Ubuntu服务器报“服务器发送了一个意外的数据包,received:3,expected:20”
  • [学习笔记] 禹神:一小时快速上手Electron笔记,附代码
  • Java stream操作流常用的方式
  • 【C#】图形图像编程
  • 埃特巴什码加解密小程序
  • Golang笔记:使用serial包进行串口通讯
  • EasyExcel 导出批注信息
  • HttpServletRequest・getContentLeng・getContentType区别
  • Matlab|【防骗帖】考虑时空相关性的风电功率预测误差建模与分析
  • 【Android面试八股文】说一说ListView卡顿的原因以及相对应的优化策略
  • Kotlin 中的内联函数
  • KALI LINUX 开启ssh免登录服务及固定ip及
  • 亮数据,一款新的低代码爬虫利器!
  • 配置OSPF认证(华为)
  • 关于ip地址的网页无法访问navigator的gpu、媒体、蓝牙等设备的解决方法
  • 深入理解外观模式(Facade Pattern)及其实际应用
  • 为什么永远不会有语言取代 C/C++?
  • Python 全栈体系【四阶】(六十一)
  • 工控必备C#
  • 【设计模式之基于特性的动态路由映射模式】
  • GB 16807-2009 防火膨胀密封件
  • 从零开始做题:老照片中的密码
  • 考研数学|张宇和武忠祥,强化能不能同时跟?
  • 【机器学习】——【线性回归模型】——详细【学习路线】
  • 【mysql】常用操作:维护用户/开启远程/忘记密码/常用命令
  • 引领AI新时代:深度学习与大模型的关键技术
  • STL——常用算法(二)