今天写项目遇到一个问题 我的项目套了很多层flex盒子 且外面不知道多少层处也有个溢出显示滚动条的样式 导致我后续的组件的溢出显示滚动条的样式overflow: auto失效了(主要是我没有用固定宽高的写法,固定宽高就不会产生这样的问题 我是因为flex:1用多了) 一直撑开父元素 且用的滚动条一直是外面不知道多少层的滚动条 css上不知如何解决故用vue封了一个组件来临时解决一下
//组件如下
<template>
<div style="height: 100%; flex: 1;" ref="parentBox">
<div :style="{ height: `${hightY}px` }">
<slot v-if="hightY"></slot>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
const parentBox = ref<HTMLDivElement | null>(null)
const hightY = ref<number>(0)
function getParentBoxHeight() {
if (parentBox.value) {
nextTick(() => {
const height = parentBox.value?.offsetHeight || 0
console.log('父盒子的高度:', height)
hightY.value = height
})
}
}
const debounce = <T extends (...args: any[]) => void>(fn: T, delay: number): T => {
let timer: ReturnType<typeof setTimeout> | null = null;
return ((...args: Parameters<T>) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
}) as T;
};
const debouncedCalculateTableHeight = debounce(getParentBoxHeight, 200);
onMounted(() => {
getParentBoxHeight();
window.addEventListener('resize', debouncedCalculateTableHeight);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', debouncedCalculateTableHeight);
});
</script>
<style scoped></style>
//使用如下
<div style="overflow: auto;flex:1;display:flex;">
<ParentBox>
<div style="height: 1000px;">12321</div>
</ParentBox>
</div>