bucle forEachr para generar múltiples gráficos echarts de forma asincrónica
demanda:
- Necesita recorrer la matriz para iniciar múltiples solicitudes para generar múltiples gráficos echarts
- La cantidad de datos es demasiado grande y los resultados de la consulta de caché de front-end se guardan durante 1 minuto
Utilizo el marco vue, pero creo un método id document.getElementById () para obtener la estructura dom,
generar dinámicamente el id
en un bucle , obtener los datos del gráfico de forma asincrónica en JS, obtener el id de cada dom en un bucle y luego renderice dinámicamente cada gráfico
La figura anterior usa esto. $ NextTick para resolver el problema de eharts.init () cuando el elemento del gráfico no está cargado, informará No se puede leer la propiedad 'getAttribute' de nulo, porque eharts no encontró el elemento, por lo que no puede ser Renderizado realizado.
Adjunta el código completo
<template>
<div>
<el-col :xs="24" :md="24" :lg="24" :xl="24" v-for="(item, i) in form.selectItem" :key="i" style="min-width: 300px; position: relative">
<el-col :xs="24" :md="12" :lg="12" :xl="8" v-for="(ele, indexs) in showList[item]" :key="i - indexs" style="min-width:300px;position: relative;">
<div style="position: relative">
<div class="charts-dis" :id="`chart${indexs}-${item}`" style="width: 100% !important;min-width: 200px;height: 400px;"></div>
</div>
</el-col>
</el-col>
</div>
</template>
<script>
export default {
data() {
return {
showList: {
},
form:{
selectItem:['a','b']
}
}
},
methods: {
refreshChart(){
axios.get('/user?ID=12345').then(function (response) {
this.showList={
a:[[1,'x'],[2,'y'],[3,'z']],
b:[[1,'x'],[2,'y'],[3,'z']]
}
this.form.selectItem.forEach(pItem=>{
this.showList[pItem].forEach(async (item, i)=>{
const chartData = await this.getChartDataWithCache(item, pItem);
this.$nextTick(function () {
let myChart = this.$echarts.init(
document.getElementById("chart" + i + "-" + pItem)
);
myChart.setOption(chartData, true);
});
})
})
})
.catch(function (error) {
console.log(error);
});
},
// 异步加载图表
getChartDataWithCache(item, pItem){
return new Promise((res)=>{
let postUrl=`/getChart?id=${item[0]}&p=${pItem}`;
let datas = window.sessionStorage.getItem(postUrl);
if(JSON.parse(datas)){
let urlData = JSON.parse(datas);
if (urlData.data) {
// 缓存过期时间
let date=new Date()
let s = this.timeDIff(date.format("YYYY-MM-DD HH:mm:ss"),urlData.date.format("YYYY-MM-DD HH:mm:ss"))
if (s < 2) {
res(urlData.data);
return;
}
}
}
this.getAxiosChartData(res, postUrl, item, pItem);
})
},
getAxiosChartData(res, postUrl, item, pItem){
axios.post(postUrl).then(data=>{
// 按需定义option
let option={}; //echarts 对象
// 缓存起来
window.sessionStorage.setItem(postUrl, JSON.stringify({ date: new Date(), data: obj }));
res(obj);
})
},
// 计算时间差
timeDIff(time1, time2) {
let begin1 = time1.substr(0, 10).split("-");
let end1 = time2.substr(0, 10).split("-");
let date1 = new Date(begin1[1] + -+begin1[2] + -+begin1[0]);
let date2 = new Date(end1[1] + -+end1[2] + -+end1[0]);
let m = parseInt(Math.abs(date2 - date1) / 1000 / 60);
let min1 =
parseInt(time1.substr(11, 2)) * 60 + parseInt(time1.substr(14, 2));
let min2 =
parseInt(time2.substr(11, 2)) * 60 + parseInt(time2.substr(14, 2));
let n = min2 - min1;
let minutes = m + n;
return minutes;
},
},
mounted: function (){
this.refreshChart();
}
}
</script>