解决Echarts设置宽度为100%发现宽度变为100px的问题
当 ECharts 图表在选项卡切换后宽度变为 100px,这通常是由于以下原因导致的:
主要原因
选项卡切换时,图表容器被隐藏,ECharts 无法获取正确的容器尺寸
图表初始化时容器可能处于隐藏状态
切换后没有重新调整图表大小
使用官方插件解决:
//echarts 引入一下
import resizeDetector from 'element-resize-detector';
const observer = resizeDetector();mounted() {this.initChartsTiaoxingtu(); //条形图图函数,里面含了后端请求的数据和options相关的初始化this.initChartsBingtu(); //饼图函数,里面含了后端请求的数据和options相关的初始化let tiaoxingtu=echarts.init(this.$refs['tiaoxingtu']);let bingtu=echarts.init(this.$refs['bingtu']);let that=this;// 监听饼图容器observer.listenTo(this.$refs.bingtu, () => {that.$nextTick(function(){this.$forceUpdate();bingtu.resize();})});// 监听条形图容器observer.listenTo(this.$refs.tiaoxingtu, () => {that.$nextTick(function(){this.$forceUpdate();tiaoxingtu.resize();})});},beforeDestroy() {// 移除监听observer.removeListener(this.$refs.tiaoxingtu);observer.removeListener(this.$refs.bingtu);},
observer.listenTo
的第一个参数是 DOM 元素(通过this.$refs.xxx
获取)。需要为每个图表容器单独调用
listenTo
。