首页 > 解决方案 > getBoundingClientRect 不是 vueJs 上的函数

问题描述

当我将光标移到 div 上时,我想找到它的顶部和底部边缘。div 是动态生成的。但是,它产生了错误消息

getBoundingClientRect 不是函数

<template>
    <div>
        <div v-for="(i, index) in divs" :key="index">
            <div :ref="'ref_' + index" @mouseover="divDragOver($event, index)">
                This is div {{ index }}
            </div>
        </div>        
    </div>
</template>

<script>

export default{
  methods: {
    divDragOver(e, i){
      var divTop = this.$refs["ref_" + i].getBoundingClientRect().top;
      console.log(divTop);
    }
  }
}
</script>

标签: javascriptvue.jsvuejs2

解决方案


您可以event.target像其他用户建议的那样使用,我认为这是最干净的方式

<template>
  <div>
    <div v-for="(i, index) in divs" :key="index">
      <div ref="myDiv" @mouseover="divDragOver">This is div {{ index }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return { divs: [1, 2, 3, 4] };
  },
  methods: {
    divDragOver(event) {
      console.log(event.target); // this will be your mouseover div
    }
  }
};
</script>

但是,对于您的问题,基于 Vue.js文档

ref与 一起使用时,v-forref将得到一个包含镜像数据源的子组件的数组。

因此,您不必在ref创建时使用索引,而您最终会得到divs.length数组,它们的第一个元素将作为您的参考。

如果您必须使用refs

<template>
  <div>
    <div v-for="(i, index) in divs" :key="index">
      <div ref="myDiv" @mouseover="divDragOver($event, index)">This is div {{ index }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return { divs: [1, 2, 3, 4] };
  },
  methods: {
    divDragOver(e, i) {
      console.log(this.$refs.myDiv); // this will be an array with all your refs, use i to access
    }
  }
};
</script>

所以你得到了一个错误,因为你的元素ref打开了this.$refs["ref_" + i][0]


推荐阅读