当屏幕大小发生变化,echarts没有进行自适应,我们可以使用它的resize()方法去解决。
当echarts的组件放在el-tabs里面的el-tab-pane切换时,echarts的自适应会跟不上,所以每次回到echarts重新调用resize()方法
<template>
<div>
<div @click="tableShowClick"> 5656div>
<charts ref="charts" :charts-data="tableData">charts>
div>
template>
<script>
import Charts from "./charts";
export default {
methods:{
// 当因为echarts 外的因素,并非el-tab-pane的切换,而是与echarts同一个层内其它的因素导致echarts需要重新进行自适应时的操作。
tableShowClick(){
this.tableShow = !this.tableShow;
setTimeout(() => {
this.$refs.charts.resize();
}, 2);
},
}
}
script>
charts.vue
<template>
<div class="echarts">div>
template>
<script>
import echarts from "echarts";
// require('echarts/theme/macarons') // echarts theme
import resize from "../../../../dashboard/mixins/resize";
export default {
mixins: [resize],
props: {
chartsData: {
type: Object,
default: () => ({}),
},
autoResize: {
type: Boolean,
default: true,
},
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "100%",
},
},
data() {
return {
chart: null,
data: [],
series: [],
};
},
beforeDestroy() {
if (!this.chart) {
return;
}
this.chart.dispose();
this.chart = null;
},
watch: {
chartsData: {
handler(val) {
this.initChart(val);
},
deep: true,
}
},
methods: {
initChart(data) {
this.chart = echarts.init(this.$el);
let option = {
series: [
// 单独控制某条柱状图的颜色
{
type: "bar",
itemStyle: {
normal: {
color: function (params) {
// console.log(params);
if (params.name == new Date().getFullYear()) {
return "red";
} else {
return "black";
}
},
},
},
},
]
}
// 避免重复促发控制图例显示隐藏的操作
this.chart.off("legendselectchanged");
// 控制图例显示隐藏
this.chart.on("legendselectchanged", (e) => {
var change = this.chart.getOption();
let name = "";
let yTitle = "";
let selected = {};
if (e.name.indexOf("水位") != -1) {
name = "水位";
if (e.selected[data.zTitle]) {
this.$set(selected, data.qTitle, false);
this.$set(selected, "10年水位均值", true);
this.$set(selected, "10年流量均值", false);
} else if (e.selected["10年水位均值"]) {
this.$set(selected, data.zTitle, true);
this.$set(selected, data.qTitle, false);
this.$set(selected, "10年流量均值", false);
}
} else {
name = "流量";
if (e.selected[data.qTitle]) {
this.$set(selected, data.zTitle, false);
this.$set(selected, "10年水位均值", false);
this.$set(selected, "10年流量均值", true);
} else if (e.selected["10年流量均值"]) {
this.$set(selected, data.zTitle, false);
this.$set(selected, data.qTitle, true);
this.$set(selected, "10年水位均值", false);
}
}
switch (name) {
case "水位":
yTitle = "水位(m)";
break;
case "流量":
yTitle = "流量(m³/s)";
break;
}
this.chart.setOption({
yAxis: { name: yTitle }, // 改变y轴的name
legend:{
selected:selected // 改变legend的selected状态
}
});
});
this.chart.clear();
this.chart.setOption(option);
}
}
}
script>
<style lang="scss" scoped>
.echarts {
width: 100%;
height: calc(100vh - 170px); // 设定了高度那么echarts的自适应更顺滑,如果没必要使用resize()方法的话,直接设定该高度便可
}
style>