vue3动态监听div高度案例

案例场景

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

实践代码案例

HTML部分
<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部分
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)
.device-item .left-bar {
  width: 2px;            // 宽度
  margin-right: 0.2rem;  // 距离
}

注意:

  • 使用 nextTick 确保 DOM 渲染完成后再更新 contentHeights。这能保证获取到准确的高度信息
  • 给 .left-bar 设置一个默认高度(例如 30px)来确保它始终可见,即使计算出来的高度是 0 时。你可以调试默认高度,并逐步确保 contentHeights 数组能够正常更新
  • contentRefs 是一个数组,用来存储每个 .content 的引用。由于 v-for 渲染的组件是异步的,可能 contentRefs 没有及时更新,导致没有正确获取到每个 .content 的高度
### Vue3 中实现键盘事件监听Vue3 中,可以通过多种方式实现在组件内监听键盘事件的功能。下面展示两种常见的方式。 #### 使用 `@keyup` 或者 `@keydown` 模板指令绑定事件处理器 通过模板内的 v-on 指令可以方便地为 DOM 绑定事件监听器。这里给出一个简单的例子,当按下特定键时更改页面上的计数器数值: ```html <script setup> import { ref, onMounted, beforeUnmount } from &#39;vue&#39; const keyCounter = ref({ ArrowUp: 0, ArrowDown: 0 }) function handleKeydown(event) { switch (event.key) { case "ArrowUp": keyCounter.value.ArrowUp += 1; break; case "ArrowDown": keyCounter.value.ArrowDown += 1; break; } } // 添加全局事件监听器 onMounted(() => window.addEventListener(&#39;keydown&#39;, handleKeydown)) // 移除全局事件监听器以防内存泄漏 beforeUnmount(() => window.removeEventListener(&#39;keydown&#39;, handleKeydown)) </script> <template> <button @click="keyCounter.ArrowUp++">Simulate Up Key Press</button> <button @click="keyCounter.ArrowDown++">Simulate Down Key Press</button> <p>Up arrow pressed {{ keyCounter.ArrowUp }} time(s).</p> <p>Down arrow pressed {{ keyCounter.ArrowDown }} time(s).</p> </template> ``` 此代码片段展示了如何利用 `ref()` 创建响应式的数据属性,并且使用 `onMounted` 和 `beforeUnmount` 生命周期钩子来管理事件监听器的添加与移除[^1]。 #### 结合计算属性和样式动态调整界面状态 另一个更复杂的案例涉及到了根据不同的按键改变整个网页背景的颜色。这通常涉及到定义一组预设好的颜色映射表以及相应的处理逻辑。如下所示: ```html <script setup> import { ref, reactive, computed, onMounted, beforeUnmount } from &#39;vue&#39;; let currentColor = ref(&#39;#ffffff&#39;); const colorKeys = reactive({ a: &#39;#ffcccc&#39;, s: &#39;#ccffff&#39;, d: &#39;#d9bfff&#39; }); function changeBackgroundColor(event){ let newColor = colorKeys[event.key]; if(newColor !== undefined){ currentColor.value = newColor; } } onMounted(() => document.body.style.backgroundColor = currentColor.value); onMounted(() => addEventListener(&#39;keydown&#39;, changeBackgroundColor)); beforeUnmount(() => removeEventListener(&#39;keydown&#39;, changeBackgroundColor)); </script> <style scoped> body{ transition: background-color .5s ease-in-out; } </style> <template> <div :style="{ backgroundColor: currentColor}"> <h2 style="text-align:center;">Press A/S/D to Change Background Color!</h2> </div> </template> ``` 上述示例不仅实现了基于按键输入修改页面样式的功能,还加入了 CSS 过渡效果使得视觉变化更加平滑自然[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值