【实用】统计类小卡片组-基于echart动态渲染实现方法

509 阅读2分钟

前言

写一个基于Echarts(百度的可视化图表库)+countTo(数字滚动组件库)可视化统计卡片组面板简单的Demo,方便jym复制即用,当然代码也存在很多待优化和提高的地方,我就抛个砖引玉!代码不一定优雅,贵在实用!

在线Demo演示

本例子用到组件

本demo例子用到了2个前端组件库Echarts countTo 具体怎么使用jym可以网上搜索,也可以看我过往写的例子juejin.cn/post/743155… 这里就不赘述了

echarts图渲染方法

注意 定义一个颜色数组color:['238, 183, 18','97, 104, 143','226, 100, 49','230, 16, 51'], 在动态渲染多个echarts折线图时我们前端做了颜色样式区分,我们先定义一个颜色数组,可以方便在实际使用的时候做配色的修改

// 卡片组渲染方法
query(){ 
  this.$nextTick(() => {  
    for (let i = 0; i < this.list.length; i++) {  
      this.doCharts(this.list[i],'charts'+i,i)
    } 
  }); 
},
// echarts图渲染方法
doCharts(chartData,chartID,index){   
  // 初始化echarts实例
  let myCharts = echarts.init(document.getElementById(chartID)); 
  // 清除echarts实例
  myCharts.clear();
  if(chartData){ 
    // 绘制图表echarts
    myCharts.setOption({
      // ----- 配置项option start ---------    
     color:['rgb('+ this.color[index] +')'],
    tooltip: {
      trigger: 'axis',
      confine: true, // 放置tips框超出
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: 'rgba('+ this.color[index] +', 0.1)',
        },
      },
    },
    grid:{
      left:0,
      right:0,
      top:0,
      bottom:0,
      containLabel: true
    },
    xAxis: {
      data: chartData.xAxisData,
      boundaryGap: false, //两边留白
      axisTick: {
        show: false, //隐藏x轴刻度
      },
      axisLabel:{
        show:false
      },  
      axisLine: {
        //y轴坐标轴,false为隐藏,true为显示
        show: false,
      },
    },
    yAxis: {  
      splitNumber:2, //y轴分隔段数量
      axisLabel:{
        show:false
      },
      axisLine: {
        //y轴坐标轴,false为隐藏,true为显示
        show: false,
      },
      splitLine: {
        show:false, 
      },
    },  
    series: [
      {
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: chartData.seriesData,
        lineStyle: {  
          color: 'rgb('+ this.color[index] +')', // 设置线条颜色为红色  
          width:1,
          shadowColor:'rgba('+ this.color[index] +', 0.1)',
          shadowBlur:9,
          shadowOffsetY:10
        },
        areaStyle:{
         color: new echarts.graphic.LinearGradient(  
            0, 0, 0, 1,  
            [  
              { offset: 0, color: 'rgba('+ this.color[index] +', 0.1)' }, // 渐变色的起始颜色  
              { offset: 0.9, color: 'rgba('+ this.color[index] +', 0)' } // 渐变线的结束颜色  
            ]  
          )   
        },
      } 
    ]         
      // ----- 配置项option end -----------  
    });
  } else {
    myCharts.setOption({
      title:{
        text:'暂无数据',
        x:'center',
        y:'center',
        textStyle: { 
            color: '#909399',
            fontSize: 14,
            fontWeight: 'normal',
            fontFamily: 'Microsoft YaHei'
        },
      }
    })
  }
  // echarts自适应
  window.addEventListener('resize', function () {  
    myCharts.resize(); 
  });
}