不推荐使用grid布局,不清楚为什么左边一列的不会自适应,换成flex布局就可以了
主要方法借助中的getInstanceByDom方法
完整代码:
<template><div class="statis"><div class="content" ><!-- v-for 遍历父级div--><div class="main" v-for="(item,index) in echartsData" :key="index"><!--自定义宽高的dom,用于放置图表--><div class="bar"></div><img class="title-bg" src="@/assets/img/title-bg.png"/></div></div></div>
</template>
<script>
import elementResizeDetectorMaker from "element-resize-detector";export default {name: "test",data() {return {observer: null,titleIcon:require('@/assets/img/title-bg.png'),echartsData: [{title:'标题1换个环境官方',data: [{ value: 20, name: '数据1' },{ value: 300, name: '数据2' },{ value: 300, name: '数据3' }],},{title:'环境官方',data: [{ value: 20, name: '数据1' },{ value: 300, name: '数据2' }],},{title:'官方',data: [{ value: 20, name: '数据1'},{ value: 300, name: '数据2'}],},{title:'标题1换个环境官方',data: [{ value: 20, name: '数据1'},{ value: 300, name: '公共 部分' }],}],color: ['#5B8FF9', '#ca2df5', '#42CE92', '#f96950', '#047ff5'],//颜色列表}},methods: {// 方法:绘制柱状图drawBar() {var myEchart = document.getElementsByClassName('bar'); //获取类名//此处for循环多次初始化 echarts 实例for (var i = 0; i < myEchart.length; i++) {var myChart = this.$echarts.init(myEchart[i]) //初始化echarts实例要在for循环内if(myChart){let option = {title: {text: this.echartsData[i].title,left: 40,top:'20',textStyle: {color:'#383838',fontSize: 16, }},tooltip: {trigger: 'item'},legend: {top: '50',left: 'center'},series: [{type: 'pie',radius: ['40%', '55%'],center: ['50%', '60%'], // 调整饼图位置data: this.echartsData[i].data,itemStyle:{normal:{label:{show: true,formatter: '{b} : {c} ({d}%)'},labelLine :{show:true},color: function (colors) {var colorList = ['#73DEB3','#578EF8','#9A60B4','#ef6567','#f9c956','#3BA272'];return colorList[colors.dataIndex];}}}}] }//使用刚指定的配置项和数据显示图表myChart.setOption(option)// window.addEventListener("resize", () => {// myChart.resize();// })}// const echartAll = document.getElementsByClassName('bar')// window.onresize = function() {// for (let i = 0; i < echartAll.length; i++) {// var myChart = this.$echarts.init(echartAll[i])// myChart.resize()// }// }}},// 处理多个图形的自适应getEchartObj() {var myEchart = document.getElementsByClassName('bar'); //获取类名for (var i = 0; i < myEchart.length; i++){console.log('myEchart[i]',myEchart[i]);let _ref= myEchart[i];//遍历生成的折线图的Domlet myEchars = _ref?this.$echarts.getInstanceByDom(_ref):undefined;if(myEchars!== undefined){myEchars.resize();}}},},mounted() {//调用绘制柱状图的方法this.$nextTick(()=>{this.drawBar()})this.$nextTick(()=>{window.onresize = ()=>{this.getEchartObj()}})}}
</script><style scoped>.content {display: flex;/* grid-template-columns: 1fr 1fr 1fr; */gap: 20px;flex-wrap: wrap;}.main {width:calc((100% - 46px)/3);border: 1px solid #D0D0D0;height: 360px;background-color: #FFFFFF;position: relative;}.title-bg{position:absolute;top:23px;left:20px;}.main .bar {width: 100%;height: 100%;}
</style>