vue3动态监听div高度案例

案例场景

场景描述:现在左边的线条长度需要根据右边盒子的高度进行动态变化

实践代码案例

HTML部分
javascript 复制代码
<div v-for="(device, index) in devices" :key="index">
        <!-- 动态设置 .left-bar 的高度 -->
        <div class="left-bar" :style="{ height: `${contentHeights[index] || 30}px` }"></div>
        <div :ref="(el) => { contentRefs[index] = el as HTMLElement }">
          <span>设备编号:{{ device.code }}</span>
          <span>异常信息:{{ device.info }}</span>
        </div>
</div>
JS部分
javascript 复制代码
import { reactive, toRefs, ref, onMounted, watch, nextTick } from 'vue';

interface Device {
  code: string;
  status: string;
  info: string;
}

const state = reactive({
  devices:[
        {
          code: 'JS23053001',
          status: '异常',
          info: '提升激光仪通讯故障 提升激光仪通讯故障 备用(从站数据故障) 备用(从站数据故障)'
        },
        {
          code: 'JS23053002',
          status: '异常',
          info: '货物左超 过载保护 断绳保护 超速保护 行走超限 升降超限'
        },
        { code: 'JS23053003', status: '正常', info: '正常' },
        { code: 'JS23053003', status: '正常', info: '正常' },
        {
          code: 'JS23053003',
          status: '异常',
          info: '行走变频器通讯故障 行走变频器通讯故障 货叉1变频器通讯故障'
        }
      ],
});

const { devices } = toRefs(state);

// 用于存储每个 content 元素的引用
const contentRefs = ref<(HTMLElement | null)[]>([]);

// 存储每个设备的 .content 元素的高度
const contentHeights = ref<number[]>([]);

// 更新每个设备的 content 高度
const updateContentHeight = () => {
contentHeights.value = contentRefs.value.map(contentRef => {
    // 获取每个 content 元素的高度
    return contentRef ? contentRef.clientHeight : 0;
  });
};

// 监听设备列表变化,重新更新高度
watch(() => state.devices, () => {
  nextTick(() => updateContentHeight()); // 确保 DOM 渲染完成后获取高度
}, { immediate: true });
Style部分(left-bar)
javascript 复制代码
.device-item .left-bar {
  width: 2px;            // 宽度
  margin-right: 0.2rem;  // 距离
}

注意:

  • 使用 nextTick 确保 DOM 渲染完成后再更新 contentHeights。这能保证获取到准确的高度信息
  • 给 .left-bar 设置一个默认高度(例如 30px)来确保它始终可见,即使计算出来的高度是 0 时。你可以调试默认高度,并逐步确保 contentHeights 数组能够正常更新
  • contentRefs 是一个数组,用来存储每个 .content 的引用。由于 v-for 渲染的组件是异步的,可能 contentRefs 没有及时更新,导致没有正确获取到每个 .content 的高度
相关推荐
bug总结25 分钟前
vue+A*算法+canvas解决自动寻路方案
前端·vue.js·算法
LYFlied31 分钟前
Vue版本演进:Vue3、Vue2.7与Vue2全面对比
前端·javascript·vue.js
VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue非遗传承文化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Dwzun1 小时前
基于SpringBoot+Vue的农产品销售系统【附源码+文档+部署视频+讲解)
数据库·vue.js·spring boot·后端·毕业设计
JIngJaneIL2 小时前
基于Java+ vueOA工程项目管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
爱看书的小沐2 小时前
【小沐学WebGIS】基于Three.JS绘制二三维地图地球晨昏效果(WebGL / vue / react )
javascript·vue.js·gis·webgl·three.js·opengl·晨昏线
疯狂的沙粒2 小时前
Vue 前端大屏做多端屏幕适配时,如何让其自动适配多种不同尺寸的屏幕?
前端·javascript·vue.js
沟通QQ8762239652 小时前
有限元仿真模型仿真模型-基于COMSOL多物理场耦合仿真的变压器流固耦合及振动噪声分析 1、变...
html
江公望3 小时前
HTML5 History 模式 5分钟讲清楚
前端·html·html5
A24207349303 小时前
使用jQuery动态操作HTML和CSS
css·html·jquery