vue3项目 怎么获取页面 div的高度 4个盒子的高度总和,给外边的父盒子
时间: 2024-04-15 14:30:52 浏览: 186
你可以使用 Vue 3 中的 ref 和 reactive 来获取页面 div 的高度。首先,在 Vue 组件中,通过 ref 创建一个对应的引用变量来获取 div 元素的引用。然后,使用 reactive 创建一个响应式对象来保存盒子的高度总和。接下来,可以通过监听 div 元素的变化来更新盒子的高度总和,并将其赋值给父盒子。
以下是一个示例代码:
<template>
<div>
<div ref="box1">...</div>
<div ref="box2">...</div>
<div ref="box3">...</div>
<div ref="box4">...</div>
<div ref="parentBox" :style="{ height: boxHeight + 'px' }">...</div>
</div>
</template>
<script>
import { ref, reactive, onMounted } from 'vue';
export default {
setup() {
const box1 = ref(null);
const box2 = ref(null);
const box3 = ref(null);
const box4 = ref(null);
const parentBox = ref(null);
const boxHeight = reactive({
totalHeight: 0,
});
const updateBoxHeight = () => {
const height1 = box1.value.offsetHeight;
const height2 = box2.value.offsetHeight;
const height3 = box3.value.offsetHeight;
const height4 = box4.value.offsetHeight;
boxHeight.totalHeight = height1 + height2 + height3 + height4;
};
onMounted(() => {
updateBoxHeight();
window.addEventListener('resize', updateBoxHeight);
});
return {
box1,
box2,
box3,
box4,
parentBox,
boxHeight,
};
},
};
</script>
在上面的示例代码中,通过 ref 创建了 box1
、box2
、box3
、box4
和 parentBox
引用变量,分别对应页面中的四个盒子和父盒子。使用 reactive 创建了一个响应式对象 boxHeight
来保存盒子的高度总和。在 updateBoxHeight
函数中,通过获取每个盒子的 offsetHeight
来计算盒子的高度总和,并将其赋值给 boxHeight.totalHeight
。在组件的 setup
钩子函数中,通过监听窗口的 resize 事件来更新盒子的高度总和。
最后,在父盒子上使用 :style="{ height: boxHeight + 'px' }"
来绑定父盒子的高度,实现将盒子的高度总和赋值给父盒子的效果。