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

Nuxt应用中访问div高度时报Cannot read properties of undefined错误如何解决

报错原因

  • client-only 包裹的组件只会在客户端渲染,父组件触发mounted钩子时,client-only内部的组件还未完成挂载,此时$refs.item1为undefined
  • Vue 2 中v-for循环里绑定的动态ref会自动生成数组结构,直接访问this.$refs.item1.clientHeight相当于访问数组的clientHeight属性,自然不存在
  • 没有做非空校验,当ItemsArray长度小于2时,item1这个ref本身就不存在

修复方案

  1. 把获取高度的逻辑放到client-only的挂载完成回调中,配合$nextTick确保DOM完全渲染
  2. 正确读取v-for生成的ref数组,加上非空校验避免报错

修改后的完整代码如下:

<template>
  <div class="grid grid-cols-3">
    <client-only @mounted="getItemHeight">
      <Item
        v-for="(item, itemIndex) in ItemsArray"
        :key="`item-${itemIndex}`"
        v-bind="item"
        :ref="`item${itemIndex}`"
      />
    </client-only>
  </div>
</template>

<script>
export default {
  data() {
    return {
      itemHeight: 0,
    }
  },
  methods: {
    async getItemHeight() {
      // 等待DOM更新完成
      await this.$nextTick()
      // 先判断ref存在再访问,数组取第一项,可选链做兼容兜底
      this.itemHeight = this.$refs.item1?.[0]?.clientHeight || 0
    }
  }
}
</script>

如果需要获取循环内所有Item的高度,遍历对应ref数组读取属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:15:02