javascript - 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>
解决方案
您可以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-for
您ref
将得到一个包含镜像数据源的子组件的数组。
因此,您不必在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]
推荐阅读
- python - 如何在使用 CountVectorizer 制作训练数据集时修复“numpy.ndarray”错误?
- apache-spark - 如何停止在函数内部创建的 SparkContext?
- java - 如何使用 1:n 关系将数据批量插入到两个表中?
- python-3.x - 使用 Pandas (Python) 更改单元格值
- c# - 允许用户选择要使用的代码实现
- c# - Backgroundworker progresschanged 事件 c#
- ios - 重用段控件
- apache-camel - Camel-Bindy (2.21.2) 固定长度解组似乎忽略了 trim=true 注释
- aws-sam - 如何获取给定已部署资源的资源 ID?
- android - 如何使用 CustomFilter 和 CustomAdapter 将输入文本放在 EditText 上