如何快速开始进行echart组件开发

1、定义chart组件

<template>
  <div ref="chart"></div>
</template>
<script>
import elementResizeDetector from "element-resize-detector";
import * as echarts from "echarts/core";
import { LineChart, BarChart, PieChart, GraphChart, LinesChart } from "echarts/charts";
import {
  GridComponent,
  SingleAxisComponent,
  TooltipComponent,
  AxisPointerComponent,
  TitleComponent,
  LegendComponent,
  DataZoomComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";

echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  SingleAxisComponent,
  GridComponent,
  AxisPointerComponent,
  BarChart,
  LineChart,
  PieChart,
  GraphChart,
  LinesChart,
  DataZoomComponent,
  CanvasRenderer,
]);

export default {
  name: "viChart",
  props: {
    options: {
      type: Object,
      required: true,
    },
    isClear: {
      type: Boolean,
      default: true,
    },
  },
  // model: {
  //   prop: "myChart",
  //   event: "setModel",
  // },
  data() {
    return {
      myChart: null,
    };
  },
  beforeDestroy() {
    this.dispose();
  },
  methods: {
    watchOptions() {
      this.$watch("options", this.setOption, { deep: true });
    },
    init() {
      this.myChart = echarts.init(this.$refs.chart);
      this.setOption();
      // 监听echart的点击事件,点击元素
      this.myChart.on("click", params => {
        this.$emit("getChartObjOnClick", params, this.myChart);
      });
      // 监听echart的点击事件,getZr()方法可以监听到整个画布的点击事件
      this.myChart.getZr().on("click", params => {
        this.$emit("getChartPanelOnClick", params, this.myChart);
      });
    },
    resize() {
      if (!this.myChart) return;
      this.myChart.resize();
    },
    setOption() {
      if (!this.myChart || Object.keys(this.options).length === 0) return;
      if (this.isClear) {
        this.myChart.clear();
      }
      this.myChart.setOption(this.options);
    },
    dispose() {
      if (!this.myChart) return;
      this.myChart.dispose();
    },
  },
  mounted() {
    this.init();
    this.watchOptions();
    this.erd = elementResizeDetector();
    this.erd.listenTo(this.$refs.chart, this.resize);
  },
  beforeDestroy() {
    this.erd.removeListener(this.$refs.chart);
  },
};
</script>

 2、定义常见echart场景

// 饼状图颜色
const colors = ["#5B8FF9", "#5AD8A6", "#5D7092", "#F6BD16", "#E8684A", "#6DC8EC", "#9270CA", "#FF9D4D", "#269A99", "#FF99C3"];
// legend的大小
const itemHeight = 8;
const itemWidth = 11;

// 饼图(环形图,中心显示名称和数值,有标签名和标签连线)
const pieOptionFun = (options = {}) => {
  const pieOption = {
    title: {
      text: ["{name|名称}", "{value|0}"].join("\n"),
      top: options.titleTop || "center",
      left: options.titleLeft || "50%",
      textAlign: "center",
      textStyle: options.textStyle  || {
        rich: {
          value: {
            color: "#555",
            fontSize: 20,
            lineHeight: 24,
          },
          name: {
            color: "#555",
            fontSize: 14,
            lineHeight: 35,
          },
        },
      },
    },
    tooltip: {
      trigger: "item",
      confine: true,
      formatter: "{b}: {c} (占比{d}%)",
    },
    legend: {
      type: "scroll",            // 设置图例翻页
      orient: "vertical",
      right: "0%",
      icon: "circle",
      itemHeight,
      itemWidth,
      textStyle: {
        color: "#8C8C8C",
        rich: {
          nameCls: {
            fontWeight: 400,
            fontSize: 14,
            padding: [5, 0, 5, 0],
            width: options.richWidth || 80,
          },
          valueCls: {
            fontSize: 12,
            padding: [0, 0, 0, 0],
            width: options.valueWidth || 40,
            textAlign: "center",
          },
        },
      },
    },
    grid: {
      left: "0%",
      right: "0%",
      bottom: "0%",
      top: options.gridTop || "0%",
      containLabel: true,
    },
    color: colors,
    series: [
      {
        type: "pie",
        startAngle: options.seriesStartAngle || 90,
        radius: options.seriesRadius || ["45%", "65%"],
        center: options.seriesCenter || ["50%", "50%"],
        label: {
          show: false,
        },
        data: [
          // { name: "克莱因壶", value: 3.5 },
          // { name: "投资最重要的事", value: 2.8 },
          // { name: "简读中国史", value: 1.7 },
          // { name: "你当像鸟飞往你的山", value: 1.4 },
          // { name: "表象与本质", value: 0.5 },
          // { name: "其它", value: 3.8 }
        ],
      },
    ],
  };
  return pieOption;
};

// 柱状图,类型过多需要分页
const barOptionFun = (options = {}) => {
  const barOption = {
    title: {
      text: "",
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: "{b}<br />数量: {c}%",
    },
    legend: {
      right: "0%",
      itemHeight,
      itemWidth,
    },
    xAxis: {
      type: "category",
      data: [], // ["Hannah Krause", "Zhao Qian", "Jasmin Krause", "Li Lei", "Karle Neumann", "Adrian Groß", "Mia Neumann"],
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        interval: 0, // 坐标轴刻度标签的显示间隔,在类目轴中有效。默认会采用标签不重叠的策略间隔显示标签。可以设置成 0 强制显示所有标签。
        formatter: (params) => {
          let newParamsName = params;
          if (options.xAxisLabelLength) { // 表示是否截取数据
            if (params.length > options.xAxisLabelLength) {
              newParamsName = `${params.slice(0, options.xAxisLabelLength - 1)}...`;
            }
          }
          return newParamsName; // 将最终的字符串返回
        },
      },
    },
    yAxis: {
      type: "value",
      alignTicks: true,
      axisLine: {
        show: true,
      },
      axisLabel: {
        formatter: "{value}",
      },
    },
    grid: {
      left: "0%",
      right: "0%",
      bottom: "10%",
      top: "10%",
      containLabel: true,
    },
    color: ["#eecb5f"],
    series: [
      {
        type: "bar",
        barMaxWidth: "30",
        data: [], // [41, 20, 52, 37, 25, 19, 71]
      },
    ],
  };
  return barOption;
};

// 折线图
const lineOptionFun = (options = {}) => {
  const lineOption = {
    title: {
      text: "",
    },
    tooltip: {
      trigger: "axis",
      formatter: "",
      confine: true,
    },
    legend: {
      top: 0,
      right: 0,
      icon: "rect",
      itemHeight,
      itemWidth,
    },
    color: options.colors || colors,
    xAxis: {
      type: "category",
      data: [],
      // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        interval: 0, // 坐标轴刻度标签的显示间隔,在类目轴中有效。默认会采用标签不重叠的策略间隔显示标签。可以设置成 0 强制显示所有标签。
        color: "#000000",
      },
    },
    yAxis: {
      name: options.yAxisName || "",
      nameTextStyle: options.nameTextStyle || undefined,
      type: "value",
      alignTicks: true,
      axisLine: {
        show: options.yAxisAxisLine,  // 是否显示y轴坐标轴轴线
      },
      axisLabel: {
        color: "#000000"
      }
    },
    grid: {
      left: options.gridLeft || "2%",
      right: "2%",
      bottom: options.gridBottom || "5px",
      top: options.gridTop || "10%",
      containLabel: true,
    },
    series: [
      // {
      //   name: "Email",
      //   type: "line",
      //   smooth: true,
      //   data: [20, 132, 101, 134, 90, 230, 110]
      // },
      // {
      //   name: "Union Ads",
      //   type: "line",
      //   smooth: true,
      //   data: [20, 182, 191, 234, 290, 230, 110]
      // },
    ],
  };
  return lineOption;
};

 

3、vue页面使用

// vue页面定义
<vi-chart class="echart" :options="weekAlarmOptions" @getChartObjOnClick="getChartObjOnClickWeek"></vi-chart>


// options渲染
// deepCopy()方法,表示深度拷贝
    this.weekAlarmOptions = deepCopy(
      barOption4Fun({
        xAxisLabelLength: 3,
        colors: ["#2277CC", "#9270CA", "#269A99", "#3300f9", "#6DC8EC"],
        gridBottom: "1%",
      })
    );
    // echart的点击事件获取
    getChartObjOnClickWeek(params) {
      const xxx= params.xxx;
      const query = {
      xxx
      };
      this.$router.push({ path: "/xxx", query });
    },

 

posted on 2024-08-09 17:00  紫藤萝yu  阅读(11)  评论(0编辑  收藏  举报