vue获取dom元素

希望获取每一个子元素的高度
html

    <div class="foods-wrapper" ref="foodsWrapper">
      <ul>
         <li v-for="item in goods" class="food-list food-list-hook">
           <h1 class="title">{{item.name}}</h1>
         </li>
      </ul>    
    </div>

vue逻辑

    mounted() {
      this.$nextTick(() => {
        this._calculateHeight()
      })
    },
    methods: {
      _calculateHeight() {
        let foodList = this.$refs.foodsWrapper.getElementsByClassName('food-list-hook')
        console.log(foodList)
        console.log(foodList.length)// 0
      }

_calculatrHeight中得到的foodList打印出来如下,length长度为9,但是并不能使用,打印foodList.Length长度为0,求指点
图片描述

阅读 10.8k
3 个回答

this.$nextTick放在你获取到goods数据并赋值之后

// 获取数据
this.getGoods().then(res => {
    this.goods = res.data  // 赋值 触发响应式更新
    this.$nextTick(()=>{  // DOM更新之后获取子元素
        this._calculateHeight()
    })
})

你console 是在哪console的?

别的函数内部?

你用let 声明? 别的肯定不能访问

很好奇为什么不能用 你这个dom元素数组 循环取出高度不就好了。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题