一、问题描述
Echarts图表宽高不能根据窗口变化而自适应,期望效果:
二、问题分析与解决
出现这种问题的情况可能是外层嵌套了其他UI组件库的标签,使得在初始化图表的时候找不到其对应的父级宽高。解决方法我们可以参考Echarts官方的resize()方法。以下是官网文档截图。
三、使用方法
将图表初始化以后添加监听窗口的变化,在监听回调中调用resize方法。
<template>
<Card class="content">
<div class="Echart" id="Echart"></div>
</Card>
</template>
<script>
import * as echarts from "echarts";
export default {
data() {
return {};
},
mounted() {
this.$nextTick(()=>{
this.initEcharts()
})
},
methods: {
initEcharts(){
var chartDom = document.getElementById("Echart");
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: "每日订单与用户统计",
},
tooltip: {
trigger: "axis",
},
legend: {
data: ["订单", "用户"],
},
grid: {
left: "3%",
right: "4%",
bottom: "3%",
containLabel: true,
},
toolbox: {
feature: {
saveAsImage: {},
},
},
xAxis: {
type: "category",
boundaryGap: false,
data: [
"5/10",
"5/11",
"5/12",
"5/13",
"5/14",
"5/15",
"5/16",
"5/17",
"5/18",
],
},
yAxis: {
type: "value",
},
series: [
{
name: "订单",
type: "line",
stack: "Total",
data: [120, 132, 101, 134, 90, 230, 210, 330, 310],
},
{
name: "用户",
type: "line",
stack: "Total",
data: [220, 182, 191, 234, 290, 330, 310, 330, 310],
},
],
};
option && myChart.setOption(option);
//监听窗口变化
window.addEventListener("resize", function () {
console.log("监听窗口变化")
myChart.resize();
});
}
},
};
</script>
<style lang="less" scoped>
.content {
min-height: 500px;
width: 100%;
}
.Echart {
height: 300px;
width: 100%;
flex-shrink: 0;
}
</style>
四、图表超出父元素
这通常是因为图表绘制的方法调用时机问题。在Echarts.init()时如果页面元素还没渲染完成就会出现这种问题。所以我们需要等待元素渲染完成以后再执行图表初始化方法。可以使用settimeout()或者this.$nextTick()。这里推荐使用后者。
this.$nextTick
是一个实例方法,它允许你延迟一个回调,直到下一次 DOM 更新循环结束之后执行。这意味着如果你在 Vue 的响应式数据更新后立即执行某些依赖于 DOM 的操作,你应该使用 this.$nextTick
来确保这些操作在 DOM 更新之后执行。