Vue大屏,全屏回退时,ECharts图表高度没有正确计算导致高度变高
最近在用 Vue 做大屏展示的项目,遇到一个问题,从全屏切换回来后,高度并没有正确计算,导致高度过高出现了滚动条,主要代码如下:
<div class="main-wrap"> <div class="left-col"> <div class="panel panel-border"> <div class="panel-header"> <span>测试标题</span> <button class="view-more">查看更多</button> </div> <div class="chart-dom"> <div ref="chart" style="width:100%;height:100%;"></div> </div> </div> ... </div> <div class="center-col"> ... </div> <div class="right-col"> ... </div></div>
<script>export default { mounted() { window.addEventListener('resize', () => this.resizeChart()) }, beforeDestroy() { window.removeEventListener('resize', this.resizeChart()) },}</script><style scoped lang="scss">
.main-wrap { display:grid; width: 100%; height: 100%; grid-template-columns: 30% 40% 30%; gap: 12px;}</style>先通过豆包 AI 来尝试解决一下这个问题,给出的几个方案,尝试了其中的两个(简单、感觉有效),但是并没有解决,问题还是存在,下面是尝试的豆包的解答:
方案一:ECharts 容器强制增加最大高度(核心,必加),
不要让 echarts 容器无限制被图表撑开,echarts 容器高度继承父级,并且 max-height 限制
.echarts-box { width: 100%; height: 100%; max-height: 100%; /* 重点:不能超过父容器高度 */ min-height: 0; /* Grid布局必加,允许轨道收缩,阻止内容撑大grid行 */ box-sizing: border-box;}方案四:兜底方案(极端情况:重置容器尺寸)
退出全屏时,先临时把 echarts 容器高度设为 0,再恢复,强制重置布局
document.addEventListener('fullscreenchange', () => { if(this.fullTimer) clearTimeout(this.fullTimer) this.fullTimer = setTimeout(() => { const dom = document.getElementById('echartsDom') dom.style.height = '0px' // 下一帧再恢复高度 requestAnimationFrame(()=>{ dom.style.height = '100%' myChart.resize() }) },100)})通过上两个失败的尝试后,又研究了下产生这个问题的原因,发现大概的原因是:从全屏回退时,页面的高度正常的变化,但是ECharts图表还在渲染,还保持全屏时的高度,这样就导致容器高度要比正常情况高,再进行 charts.resize(),是以错误的高度进行 resize 的,因此导致高度计算错误。
发现了原因后,再想豆包的方案四,应该能够解决这个问题,先将图表高度调整为0,再恢复到正常的高度,可结果并没效果,这应该是 resize() 的时机不对,但用的是 screenfull 插件,监听全屏标志,从根源去解决比较麻烦。
一次偶然的尝试,去掉 charts.resize() 试试看是什么效果,试验结果很完美,能够恢复到正常的高度,最后的解决方案就是:去掉了 chart.resize() 事件。
实际应用时,可以在全屏放大前取消注册 charts.resize() 事件,恢复正常屏幕后再重新注册该事件。