素材牛VIP会员
vue获取dom元素
 路***6  分类:JavaScript  人气:867  回帖:3  发布于6年前 收藏

希望获取每一个子元素的高度
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,求指点

 标签:vue.jsjavascript

讨论这个帖子(3)垃圾回帖将一律封号处理……

Lv6 码匠
蜜***园 Web前端工程师 6年前#1

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

// 获取数据
this.getGoods().then(res => {
    this.goods = res.data  // 赋值 触发响应式更新
    this.$nextTick(()=>{  // DOM更新之后获取子元素
        this._calculateHeight()
    })
})
Lv6 码匠
奇***士 移动开发工程师 6年前#2

你console 是在哪console的?

别的函数内部?

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

Lv4 码徒
郑***0 PHP开发工程师 6年前#3

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取