分两种情况
一、屏幕大小变化导致echarts容器大小变化
如缩小浏览器页面,竖屏变横屏
this.myChart1 = echarts.init(document.getElementById("mychart"));
this.myChart1.setOption(option);
//随着屏幕大小调节图表
window.addEventListener("resize", () => {
this.myChart1.resize();
});
二、屏幕大小不变但echarts容器大小变化
如菜单的折叠展开导致的主面板宽度变化,但浏览器屏幕大小是没有变的,这种情况下第一种方法不管用,则使用下述方法:
1.引入插件
npm install element-resize-detector --save
2.在所需页面导入
import elementResizeDetectorMaker from "element-resize-detector";
3.在mounted里使用
let erd = elementResizeDetectorMaker();
let that = this;
erd.listenTo(document.getElementById("echarts-box"), (element) => {
that.$nextTick(() => {
//使echarts尺寸重置
that.myChart1.resize();
that.myChart2.resize();
});
});
完整实例
<template>
<div id="echarts-box">
<div id="mychart1"></div>
<div id="mychart2" style="width: 100%;height:400px;"></div>
</div>
</template>
<script>
import * as echarts from 'echarts'
import elementResizeDetectorMaker from "element-resize-detector";
export default {
data(){
return{
myChart1: {},
myChart2: {},
}
},
mounted(){
//初始化数据
this.initCharts()
//使图表大小自适应
let erd = elementResizeDetectorMaker();
let that = this;
//echarts-box是需要监控大小的盒子
//mychart是需要变化的图表盒子
//若只有一个图表,可直接监控图表盒子
erd.listenTo(document.getElementById("echarts-box"), (element) => {
that.$nextTick(() => {
//使echarts尺寸重置
that.myChart1.resize();
that.myChart2.resize();
});
});
},
methods:{
initCharts(){
const option ={
//图表设置省略
}
this.myChart1 = echarts.init(document.getElementById("mychart1"));
this.myChart1.setOption(option);
const option2 ={
//图表设置省略
}
this.myChart2 = echarts.init(document.getElementById("mychart2"));
this.myChart2.setOption(option2);
//以下方法一实例代码,随着屏幕大小调节图表
window.addEventListener("resize", () => {
this.myChart1.resize();
this.myChart2.resize();
});
}
}
}
</script>