我的实现自适应的办法是用window.onresize监听视口的大小,变化的时候就调用chartssize()方法,在这个方法中使用getStyle(container, 'width(height)').width(height)把图表外层的div的宽高赋给图表,这样,我们只需控制外层div的自适应就好了。比如我的代码中外层是id="chartBox"的div,整体的布局通过vw,vh来控制自适应,这样视口变小时,id="chartBox"的div就会等比缩小,html会自己计算这个div的宽高,并将其赋给图表。以此让图表的大小也跟着改变。
template部分:
<div class="" id="chartBox">
<div id="container" style="width:150px;height: 150px"></div>
</div>
script部分:
drawChart() {
let myChart = this.$echarts.init(document.getElementById("container"));
var option;
option = {
title: {
text: "Referer of a Website",
subtext: "Fake Data",
left: "center",
},
tooltip: {
trigger: "item",
},
legend: {
orient: "vertical",
left: "left",
},
series: [
{
name: "Access From",
type: "pie",
radius: "50%",
data: [
{ value: 1048, name: "Search Engine" },
{ value: 735, name: "Direct" },
{ value: 580, name: "Email" },
{ value: 484, name: "Union Ads" },
{ value: 300, name: "Video Ads" },
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: "rgba(0, 0, 0, 0.5)",
},
},
},
],
};
myChart.setOption(option);
window.addEventListener('resize', myChart.resize);
},
chartssize (container,charts) {
console.log(container)
function getStyle(el, name) {
if (window.getComputedStyle) {
return window.getComputedStyle(el, null);
} else {
return el.currentStyle;
}
}
var wi = getStyle(container, 'width').width;
var hi = getStyle(container, 'height').height;
charts.style.width = wi
charts.style.height = hi
}
},
mounted() {
this.drawChart();
window.onresize = () => {
return (() => {
this.chartssize(document.getElementById("chartBox"),document.getElementById("container"));
})()
}
},