不知道大家是否遇见过 window.onresize 在实现 vue 中使用两个及以上 echarts 图表时只有最后一个图表会跟随窗口大小变化或者所有图表大小都不会变化的情况,今天我稍稍总结一下下,嘻嘻。
1、首先先来几个图表容器(总结么,id 就简单些了)
<template>
// class为容器宽高,此处省略
<div class="echarts-box">
<div class="ech-item" id="one"></div>
<div class="ech-item" id="two"></div>
<div class="ech-item" id="three"></div>
</div>
</template>
2、每个图表都要配置 option,也可以在 vue data 中配置,此处我在同级的 options.js 文件中配置一个 option(echarts官网实例) 作为例子
export const oneOption = {
title: {
text: '堆叠区域图'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: {
backgroundColor: '#6a7985'
}
}
},
legend: {
data: ['邮件营销', '联盟广告', '视频广告', '直接访问', '搜索引擎']
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis: [
{
type: 'category',
boundaryGap: false,
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
}
],
yAxis: [
{
type: 'value'
}
],
series: [
{
name: '邮件营销',
type: 'line',
stack: '总量',
areaStyle: {},
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '联盟广告',
type: 'line',
stack: '总量',
areaStyle: {},
data: [220, 182, 191, 234, 290, 330, 310]
},
{
name: '视频广告',
type: 'line',
stack: '总量',
areaStyle: {},
data: [150, 232, 201, 154, 190, 330, 410]
},
{
name: '直接访问',
type: 'line',
stack: '总量',
areaStyle: {},
data: [320, 332, 301, 334, 390, 330, 320]
},
{
name: '搜索引擎',
type: 'line',
stack: '总量',
label: {
show: true,
position: 'top'
},
areaStyle: {},
data: [820, 932, 901, 934, 1290, 1330, 1320]
}
]
};
// 为方便查看 option 内容就由大家遇到的时候对应填充了
export const twoOption = {};
export const threeOption = {};
3、将 options.js 引入 vue 文件并完成图表
<script>
import { oneOption, twoOption, threeOption } from "./option";
export default {
data() {
return {
oneOption: "",
twoOption: "",
threeOption: ""
};
},
created() {
// 由于此处只写了一个option,为模拟多个图表,用同一个option赋值
this.oneOption = JSON.parse(JSON.stringify(oneOption));
this.twoOption = JSON.parse(JSON.stringify(oneOption));
this.threeOption = JSON.parse(JSON.stringify(oneOption));
},
mounted() {
this.initCharts();
},
methods: {
initCharts () {
this.oneCharts = echarts.init(document.getElementById("one"));
this.oneCharts.setOption(this.oneOption);
this.twoCharts = echarts.init(document.getElementById("two"));
this.twoCharts.setOption(this.twoOption);
this.threeCharts = echarts.init(document.getElementById("three"));
this.threeCharts.setOption(this.threeOption);
let _this = this; // 必要代码,this指向不同
window.addEventListener("resize", () => {
_this.oneCharts.resize();
_this.twoCharts.resize();
_this.threeCharts.resize();
}, false);
}
},
// resize监听销毁,提高性能
beforeDestroy() {
this.oneCharts.clear();
this.twoCharts.clear();
this.threeCharts.clear();
}
}
</script>
温馨提示: 以上代码前提是引入 echarts 组件哦 ~~~