终于!!!,加班到现在才搞完.....
新手第一篇文章希望大家多多支持
首先是图表
整体思路:根据父级的宽高的改变使得echart跟着改变
HTML部分
<el-col id="echart_box" :span="12"> <div style="margin:auto 0" id="calendar" /> </el-col>
复制
JS部分
chartssize(){ let echartBox = document.getElementById("echart_box"); let w = echartBox.offsetWidth; // 返回元素的总宽度 let h = echartBox.offsetHeight; // 返回元素的总高度 console.log(w,h); this.myChart.resize({ width: w, height: h }); // 这个是字体 自适应大小后面会讲 this.setEchartFontSize() },
复制
CSS部分
#echart_box{ width: 100%; height: 100%; padding:0 10px; } #calendar{ width: 100%; height:360px; margin: 0 10px; }
复制
字体自适应部分
整体思路:获取其他可自适应做出改变的元素的字体大小,再计算成echart需要的大小并赋值
JS部分
setEchartFontSize(){ //获取其他元素的字体大小 let dayclass = document.getElementsByClassName("day") let fontSizeStr = window.getComputedStyle(dayclass[0]).fontSize // 例 '12px' let str = fontSizeStr.replace(new RegExp("px","g"),""); // new RegExp 加'g',删除字符串里所有的"a" 例:'12px' => '12' let num = parseInt(str); // 例 '12' => 12 this.myChart.setOption({ series: [ { label:{ fontSize:num - 2 } } ] }) }
复制
整体挂载:
mounted() { this.onChart() this.setEchartFontSize() this.chartssize() }, methods: { onChart(){ this.myChart = echarts.init(document.getElementById('calendar')) this.myChart.setOption(this.option) // 自适应大小 窗口大小变化时触发 window.addEventListener("resize",()=>{ this.chartssize() }) },
复制
注:如果不能自适应检查一下父级或者借鉴的元素本身不能做出自适应
如在以下代码报........(reading ‘type‘)的错误
window.addEventListener("resize",()=>{
// this.myChart.resize();
this.setEchartFontSize()
this.chartssize()
})
解决方法:
// shallowRef需引入 import {shallowRef} from 'vue';
this.myChart = shallowRef(echarts.init(document.getElementById('echart1')))