forEachr loop to generate multiple echarts charts asynchronously

forEachr loop to generate multiple echarts charts asynchronously

demand:

  1. Need to loop the array to initiate multiple requests to generate multiple echarts charts
  2. The amount of data is too large, and the front-end cache query results are kept for 1 minute

I use the vue framework, but I create an id document.getElementById() method to get the dom structure,
dynamically generate the id
Insert picture description here
in a loop , get the chart data asynchronously in JS, get the id of each dom in a loop, and then dynamically render each chart
Insert picture description here

The above figure uses this.$nextTick to solve the problem of eharts.init() when the chart element is not loaded, it will report Cannot read property'getAttribute' of null, because eharts did not find the element, so it cannot be performed Rendering.

Attach the complete code

<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>

Guess you like

Origin blog.csdn.net/weixin_43881166/article/details/114636811