Echarts图表初始化组件

echart 初始化组件

1.导入echarts

创建echarts.ts,按需引入

	import echarts from 'echarts';
	 export default echarts;

2.防抖函数

/**
 * 防抖函数
 * @param method
 * @param params
 */
export function debounce(method, params) {
  let timer: any = null;
  // eslint-disable-next-line func-names
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      method(params); // 即调用handlerResize,params即传入的参数eleArr
    }, 300);
  };
}

3.创建echarts公共组件

/*
porps{
   className : 自定义容器css
   id : 容器id(必填)
   height : 容器高度
   width : 容器宽度
   data : 图表数据源 ,需要符合官方柱状图的数据格式
   date : 柱状图横坐标时间
   title : 图表标题
   subtitle : 子标题
   一般title 在外部自定义,如有需要自己添加
  }

*/

<template>
  <div :id="`line${Math.random()}`" ref="chart" :class="className" :style="{ height, width }" />
</template>

<script>
import { debounce } from '@/utils/util';
import echarts from '@/plugins/echarts';

export default {
  props: {
    id: {
      type: String,
      default: 'chart',
    },
    className: {
      type: String,
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '100%',
    },
    yAxisLabel: {
      type: String,
      default: '件',
    },
    yAxisMax: {
      type: String,
      default: null,
    },
    type: {
      type: String,
      default: 'bar',
    },
    option: {
      type: Object,
      default: null,
    },
    showTitle: {
      type: Boolean,
      default: true,
    },
    subtitle: {
      type: String,
      default: '',
    },
    data: {
      type: Array,
      default: () => [],
    },
    xUnit: {
      type: String,
      default: '',
    },
    yUnit: {
      type: String,
      default: '件',
    },
    xAxisData: {
      type: Array,
      default: null,
    },
    yAxisType: {
      type: String,
      default: 'value',
    },
    // 多条数据 legend 颜色
    multiColors: {
      type: Array,
      default: null,
    },
    legend: {
      type: Object,
      default: null,
    },
    // 多条数据时使用,主要是不想写循环
    series: {
      type: Array,
      default: null,
    },
    // 多条数据的名称
    seriesNames: {
      type: Array,
      default: () => [],
    },
    color: {
      type: String,
      default: '',
    },
    // 图表是否旋转(X,Y轴互换)
    rotate: {
      type: Boolean,
      default: false,
    },
    // x轴-可见数量(溢出拖动)
    visibleXNum: {
      type: Number,
      default: null,
    },
    // x轴-旋转后的刻度
    xAxisRotate: {
      type: Number,
      default: 0,
    },
    // X轴-是否多个
    multiXAxis: {
      type: Boolean,
      defalult: false,
    },
    // line-曲线
    smooth: {
      type: Boolean,
      default: false,
    },
    // line-面积图
    hasArea: {
      type: Boolean,
      default: true,
    },
    // bar-宽度
    barWidth: {
      type: Number,
      default: 30,
    },
    // bar-圆角
    barBorderRadius: {
      type: Array,
      default: () => [0],
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.resizeHanlder = () => {
      if (this.chart) {
        this.chart.resize();
      }
    };
    window.addEventListener('resize', debounce(this.resizeHanlder));
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    window.removeEventListener('resize', this.resizeHanlder);
    this.chart.dispose();
    this.chart = null;
    this.$EventBus.$off('show:dialog', {});
  },
  computed: {
    xData() {
      const arr = [];
      // 讲数据与单位拼接作为x轴参数返回
      this.data.forEach(item => {
        arr.push(item.name + this.xUnit);
      });
      return arr;
    },
  },
  methods: {
    initChart() {
      if (!this.$refs.chart) {
        return;
      }
      this.chart = echarts.init(this.$refs.chart);
      const {
        type,
        visibleXNum,
        multiColors,
        data,
        legend,
        series,
        xData,
        xUnit,
        yUnit,
        yAxisType,
        xAxisData,
        xAxisRotate,
        yAxisMax,
        barBorderRadius,
        smooth,
        barWidth,
      } = this;
      const axisPointerType = type === 'bar' ? 'shadow' : 'none';
      const endValue = visibleXNum || data.length;
      const areaStyle = this.hasArea
        ? {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: '#298aff', // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: '#F9FCF9', //   0% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          }
        : null;
      let seriesData = [];
      if (!series) {
        seriesData = [
          {
            type,
            data,
            barWidth, // 柱图宽度
            // 折线上点点的样式
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                lineStyle: {
                  color: '#8fbcf3', // 改变折线颜色
                },
                barBorderRadius, // [18, 18, 18, 18]
                // 每根柱子颜色设置
                color(params) {
                  // 顺时针,第一个参数代表右
                  const color = new echarts.graphic.LinearGradient(
                    0,
                    1,
                    0,
                    0,
                    [
                      {
                        offset: 0,
                        color: '#57A7F7', // 0% 处的颜色
                      },
                      {
                        offset: 1,
                        color: '#308AE4', // 100% 处的颜色
                      },
                    ],
                    false
                  );
                  return color;
                },
                label: {
                  show: true,
                  color: '#000',
                  fontSize: '16px',
                  position: 'top',
                },
              },
            },
            // 是否为曲线
            smooth,
            // 折线面积图,带渐变
            areaStyle,
          },
        ];
      } else {
        seriesData = series.map(m => ({
          type: m.type || type,
          name: m.name,
          data: m.data,
          barWidth: m.barWidth, // 柱图宽度
          // 折线上点点的样式
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            normal: {
              lineStyle: {
                color: m.color || '#8fbcf3', // 改变折线颜色
              },
              barBorderRadius, // [18, 18, 18, 18]
              // 每根柱子颜色设置
              color(params) {
                // 顺时针,第一个参数代表右
                const color =
                  m.color ||
                  new echarts.graphic.LinearGradient(
                    0,
                    1,
                    0,
                    0,
                    [
                      {
                        offset: 0,
                        color: m.colors ? m.colors[0] : '#57A7F7', // 0% 处的颜色
                      },
                      {
                        offset: 1,
                        color: m.colors ? m.colors[1] : '#308AE4', // 100% 处的颜色
                      },
                    ],
                    false
                  );
                return color;
              },
              label: {
                show: true,
                color: '#000',
                fontSize: '16px',
                position: 'top',
              },
            },
          },
          // 是否为曲线
          smooth,
        }));
      }
      const option = {
        color: multiColors,
        tooltip: {
          textStyle: {
            fontSize: 16,
            color: '#333030',
          },
          backgroundColor: '#fff',
          // 容器阴影
          extraCssText: 'box-shadow: 0px 0px 4px rgba(172, 172, 172, 0.7);',
          trigger: 'item', // item , axis
          axisPointer: {
            type: axisPointerType, // line , shadow , none , cross
          },
          formatter: params => {
            const { seriesName, name, value } = params;
            if (!seriesName.includes('series')) return `${seriesName}<br /> ${name}:<br />${value} ${yUnit}`;
            return `${name} ${xUnit}:<br />${value} ${yUnit}`;
          },
        },
        // 数据展示与缩放
        dataZoom: [
          {
            type: 'inside',
            show: true,
            start: 0,
            // 默认展示多少条数据
            endValue,
            xAxisIndex: [0],
            // 禁止缩放
            zoomLock: true,
          },
        ],
        // 定位
        grid: {
          // 顶部 40  为图例预留空间
          top: 40,
          left: 20,
          right: 20,
          bottom: 10,
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData || xData,
            axisLine: {
              lineStyle: {
                width: 2,
                color: '#a2abbah',
              },
            },
            axisTick: {
              // 隐藏刻度
              show: false,
            },
            axisLabel: {
              // 坐标轴刻度标签的相关设置。
              rotate: xAxisRotate,
              textStyle: {
                fontSize: 16,
                color: '#333030',
              },
              // 获取不到外部数据,暂时不知道如何配置化
              formatter(p) {
                if (p.length === 6) return `${p.substring(0, 4)}\n${p.substring(4, 6)}`;
                if (p.length > 5) return `${p.substring(0, 4)}\n${p.substring(4, p.length)}`;
                return p;
              },
            },
          },
        ],
        yAxis: [
          {
            type: yAxisType,
            // 'value' 数值轴
            // 'category' 类目轴
            // 'time' 时间轴
            // 'log' 对数轴。
            max: yAxisMax,
            // 最小分割值为1
            minInterval: 1,
            textStyle: {
              fontSize: 16,
              color: '#333030',
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              // 隐藏刻度
              show: false,
            },
            axisLabel: {
              formatter: `{value}${yUnit}`,
              color: '#fff',
              textStyle: {
                fontSize: 16,
                color: '#333030',
              },
            },
            splitLine: {
              lineStyle: {
                color: '#d8dde5',
                type: 'dotted', // solid , dashed , dotted
              },
            },
          },
        ],
        legend,
        series: seriesData,
      };
      // bar 型 是否横向删除标记

      if (this.option) {
        this.chart.setOption(this.option, true);
      } else this.chart.setOption(option, true);
      // 此处绑定点击事件,把图例内容抛出,用于数据钻取
      this.chart.off('click');

      //  删除多折线反查记录
      this.chart.resize();
      this.$emit('Onlegendselectchanged', this.chart);
      //   this.chart.on('legendselectchanged', e => {
      //     // console.log(e);

      //   });
    },
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.initChart();
        });
      },
    },
    series: {
      deep: true,
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.initChart();
        });
      },
    },
    option: {
      deep: true,
      handler(val) {
        this.initChart();
      },
    },
  },
};
</script>

4.导入数据,渲染统计图

   <lineChart class="bar" v-else :option="barOption ">   	</lineChart>
   //将option对象引入,即可渲染
 const  barOption =  {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar'
    }
  ]
};

成品图

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值