// 在 Vue 组件中获取 div 高度的示例代码
<template>
<div ref="myDiv" @click="getDivHeight">
点击我获取高度
</div>
</template>
<script>
export default {
methods: {
getDivHeight() {
// 使用 this.$refs 获取 DOM 元素
const divElement = this.$refs.myDiv;
// 获取 div 的高度
const height = divElement.offsetHeight;
console.log('div的高度:', height);
}
}
}
</script>
<style scoped>
div {
width: 200px;
height: 150px;
background-color: lightblue;
text-align: center;
line-height: 150px;
}
</style>
模板部分 (<template>
):
ref="myDiv"
给 div
元素添加一个引用,方便在 JavaScript 中通过 this.$refs.myDiv
获取该元素。@click="getDivHeight"
,当点击 div
时触发 getDivHeight
方法。脚本部分 (<script>
):
getDivHeight
,该方法通过 this.$refs.myDiv
获取到 div
元素,并使用 offsetHeight
属性获取其高度,最后将高度打印到控制台。样式部分 (<style scoped>
):
div
的宽度、高度和背景颜色,以便更直观地看到效果。下一篇:ant design vue2
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站