ECharts圖表未完全填充容器:如何解決100%高度寬度設置無效的問題?

echarts圖表未完全填充容器:100%高度寬度設置無效的解決方法

ECharts圖表未完全填充容器:如何解決100%高度寬度設置無效的問題?

在使用ECharts圖表時,經常會遇到圖表無法完全填充父容器的問題。本文分析一個典型案例,并提供解決方案。

問題描述: 開發者使用ECharts繪制圖表,但圖表未能完全填充其父容器。父容器和圖表容器都設置了height: 100%; width: 100%;,但圖表仍顯示不完整。

代碼片段:

模板代碼:

<template>   <div class="linebarchart-page">     <div class="chartbox" ref="chartbox"></div>   </div> </template>

樣式代碼:

.linebarchart-page {   height: 100%;   width: 100%;   .chartbox {     height: 100%;     width: 100%;   } }

組件注冊及使用代碼:

<div class="left-box">   當班合格/不良統計   <dv-border-box-12 style="flex: 0 1 33%"><linebarchart ref="currenttotal" style="height:100%;width:100%;" v-show="currenttotalisshow"></linebarchart></dv-border-box-12>產品合格率統計   <dv-border-box-13 style="flex: 0 1 33%"><linebarchart ref="productionpassratestatistic"></linebarchart></dv-border-box-13>產能達成率   <dv-border-box-13 style="flex: 0 1 33%"><linebarchart ref="productionachievingrate"></linebarchart></dv-border-box-13> </div>

圖表渲染代碼:

initChart(data) {   this.$nextTick(() => {     this.chartInstance = echarts.init(this.$refs.chartbox);   });   this.chartInstance.setOption({     // ...圖表配置   }); }, mounted() {   this.initChart(); },

問題根源: height: 100%; width: 100%;依賴于父元素的實際尺寸。如果父元素尺寸未確定,子元素也無法確定尺寸,導致ECharts圖表無法正確渲染。

解決方案: 監聽父容器尺寸變化,并在尺寸變化后重新調整ECharts圖表大小。可以使用$nextTick或瀏覽器窗口大小改變事件監聽,并在尺寸變化后調用echartsInstance.resize()方法。 確保.linebarchart-page元素在initChart函數執行前已具有確定的寬高。

改進后的代碼可能需要添加窗口大小改變監聽或者使用$nextTick確保父容器尺寸已確定后再初始化圖表。 例如,在mounted鉤子函數中使用$nextTick:

mounted() {   this.$nextTick(() => {     this.initChart();   }); },

或者添加窗口大小改變監聽:

mounted() {   this.initChart();   window.addEventListener('resize', this.resizeChart); }, beforedestroy() {   window.removeEventListener('resize', this.resizeChart); }, methods: {   resizeChart() {     this.chartInstance.resize();   } }

通過以上方法,可以確保ECharts圖表能夠完全填充其父容器。 選擇哪種方法取決于你的具體應用場景和需求。

? 版權聲明
THE END
喜歡就支持一下吧
點贊8 分享