vue动态设置ref,this.$ref获取不到元素的问题

4,572 阅读1分钟

在业务开发中遇到一个场景,需要动态获取一个table中每个td的高度,然后别的table中的td元素根据这个高度进行计算。

        <tr v-for="(value,idx) in item.children" :key="value.id">
          <td class="td-height" :ref="value.id">
          </td>
        </tr>

在实际操作中遇到一个问题,this.$ref获取不到想要的元素,打印之后发现this.$ref返回的对象中属性的值都是空数组。

这是由于在使用this.$ref的时候动态绑定的DOM还没有初始化,需要使用**this.$nextTick()**方法,

this.$nextTick()的作用是将方法里面的回调延迟到DOM更新之后执行,可以确保this.$ref能获取到DOM。

        this.$nextTick(() => {
          this.pointerHeight = []
          this.checkHeight = []
          this.tableData.forEach(item => {
            let height = 0;
            item.children.forEach(value => {
              height += this.$refs[value.id][0].offsetHeight
              this.checkHeight.push(this.$refs[value.id][0].offsetHeight)

            })
            this.pointerHeight.push(height)
          })

        })