dav*_*lee 7 javascript vue.js vuejs2
当我将光标移到 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>Run Code Online (Sandbox Code Playgroud)
您可以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>
Run Code Online (Sandbox Code Playgroud)
对于您的问题,根据 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>
Run Code Online (Sandbox Code Playgroud)
所以你收到错误是因为你的元素ref已打开this.$refs["ref_" + i][0]