根据需求生成一类多张echarts折线图,获取后端数据,循环动态生成,且能自适应各种窗口
1.使用常规方法只能作用于一张图,其余的不能做到自适应,如下:
window.addEventListener('resize', () => {
myChart.resize()
})
2.我们的需求是循环生成的所有图表都能做到自适应,如下:
2.1 html代码片段:
<div v-for="(item, index) in datadata" :key="index" class="roseChart" />
2.2 js代码片段 (关键代码) :
datadata:[
{inputLabel: ["pdf"],isBlank: "0",
time: ["2022-11-01 00:00:00", "2022-11-01 01:00:00", "2022-11-01 02:00:00", "2022-11-01 03:00:00"]
value: ["0.00", "0.00", "0.00", "0.00"]},
{inputLabel: ["pdf"],isBlank: "1",
time: ["2022-11-14 00:00:00", "2022-11-018 01:00:00", "2022-11-020 02:00:00", "2022-11-27 03:00:00"]
value: ["0.00", "0.00", "0.00", "0.00"]}
],
window.onresize = function() {
for (let i = 0; i < echartAll.length; i++) {
var myChart = echarts.init(echartAll[i])
myChart.resize()
}
}
2.3 循环生成图表,完整代码:
drawLine() {
var roseCharts = document.getElementsByClassName('roseChart') // 对应地使用ByClassName
for (var i = 0; i < roseCharts.length; i++) {
var myChart = echarts.init(roseCharts[i])
const option = ({
tooltip: {
trigger: 'axis'
},
title: {
text: '输入数据'
},
legend: {
data: this.datadata[i].inputLabel, // 图例
top: 10,
right: 20
},
grid: {
left: '3%',
right: '6%',
bottom: '3%',
containLabel: true
},
dataZoom: [
{
startValue: '2021-07-01'
},
{
type: 'inside'
}
],
xAxis: {
name: '日期',
type: 'category',
boundaryGap: false,
data: this.datadata[i].time
},
yAxis: {
name: '数量',
type: 'value'
},
// 三条折线就有三种series,可以更改type以改变是否为折线
series: [{
name: this.datadata[i].inputLabel,
type: 'line',
data: this.datadata[i].value
}]
})
myChart.setOption(option)
}
const echartAll = document.getElementsByClassName('roseChart')
window.onresize = function() {
for (let i = 0; i < echartAll.length; i++) {
var myChart = echarts.init(echartAll[i])
myChart.resize()
}
}
},
小结:该问题主要是因为循环生成造成的,自适应只能作用于最后生成的那个图形,要想让所有的都能自适应,需要操作每一个dom对象,通过循环获取到每个dom实例,在分别给与使用resize()方法,才能做到所有生成的图都能做到自适应。