You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useElementSize动态更新容器尺寸时height样式绑定异常问题

问题解决:绑定元素尺寸到自身style后高度显示为0的问题

问题根源

你遇到的是循环依赖导致的死锁:

  • 初始渲染时,元素还没渲染出内容高度,useElementSize返回的height是0;
  • 你通过:style把元素高度强制设为0px,元素被固定成0高度;
  • 后续useElementSize只能读到这个强制设置的0高度,再也无法获取到元素实际的尺寸变化,形成死循环。

可行解决方案

1. 给元素加初始默认高度(最简单的办法)

直接给元素设置min-height或者初始默认高度,打破初始的0高度循环:

<template>
  {{ height }}
  <div 
    :style="{ height: `${height}px` }" 
    ref="el"
    style="resize: both; overflow: auto; min-height: 200px;"
  >
    Resizeable items whoopwhoop
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useElementSize } from '@vueuse/core';

const el = ref(null);
const { height, width } = useElementSize(el);

return { height, width, el };
</script>

min-height会保证元素初始有高度,useElementSize能读到正确值,后续resize时height更新,style也会同步覆盖min-height。

2. 用独立变量延迟绑定,避免初始死锁

定义一个单独的样式高度变量,初始给默认值,只在height有效时更新:

<template>
  {{ height }}
  <div 
    :style="{ height: styleHeight }" 
    ref="el"
    style="resize: both; overflow: auto;"
  >
    Resizeable items whoopwhoop
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useElementSize } from '@vueuse/core';

const el = ref(null);
const { height, width } = useElementSize(el);
const styleHeight = ref('200px'); // 初始默认高度

// 只有当height大于0时才更新样式
watch(height, (newHeight) => {
  if (newHeight > 0) {
    styleHeight.value = `${newHeight}px`;
  }
});

return { height, width, el, styleHeight };
</script>

3. 调整useElementSize的尺寸读取逻辑

如果是自定义的useElementSize,确保它读取的是元素的内容高度(而非被inline style覆盖的计算高度)。比如改用offsetHeight或clientHeight:

// 自定义useElementSize实现示例
function useElementSize(elRef) {
  const height = ref(0);
  const width = ref(0);

  const updateSize = () => {
    if (elRef.value) {
      // offsetHeight包含padding和border,clientHeight只包含padding,按需选择
      height.value = elRef.value.offsetHeight;
      width.value = elRef.value.offsetWidth;
    }
  };

  onMounted(() => {
    updateSize();
    // 监听窗口resize
    window.addEventListener('resize', updateSize);
    // 监听元素自身resize(需要ResizeObserver)
    const observer = new ResizeObserver(updateSize);
    observer.observe(elRef.value);
  });

  onUnmounted(() => {
    window.removeEventListener('resize', updateSize);
    // 清理观察者
    observer?.disconnect();
  });

  return { height, width };
}

注意事项

可resize元素必须添加resize: both; overflow: auto;样式,否则无法拖动调整尺寸。

内容的提问来源于stack exchange,提问作者Some Name

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 02:05:30