聊聊vue3中echarts用什么形式封装最好?(代码详解)

Vue2023-04-2830 人已阅来源:网络

@charset "UTF-8";.markdown-body{position:relative;word-break:break-word;line-height:1.75;font-weight:400;font-size:15px;color:#282d36}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{line-height:1.5;margin-top:35px;margin-bottom:10px;padding-bottom:5px}.markdown-body h1{font-size:30px;margin-bottom:5px;color:#2f845e}.markdown-body h2{font-size:22px;display:inline-block;font-weight:700;background:#2f845e;color:#fff;padding:6px 8px 0 0;border-top-right-radius:6px;margin-right:2px;box-shadow:6px 3px 0 0 rgba(47,132,194,.2)}.markdown-body h2:before{content:" ";display:inline-block;width:8px}.markdown-body h2:after{content:" ";position:absolute;display:block;width:calc(100% - 32px);border-bottom:3px solid #2f845e}.markdown-body h3{font-size:18px;padding-bottom:0}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:15px}.markdown-body h6{margin-top:5px}.markdown-body p{line-height:inherit;margin-top:22px;margin-bottom:22px}.markdown-body img{max-width:100%;box-shadow:6px 6px 6px #888}.markdown-body hr{border:none;border-top:1px solid rgba(66,185,131,.15);margin-top:32px;margin-bottom:32px}.markdown-body code{word-break:break-word;border-radius:2px;overflow-x:auto;background-color:#f6ffed;color:#52c41a;font-size:.87em;padding:.065em .4em}.markdown-body code,.markdown-body pre{font-family:Menlo,Monaco,Consolas,Courier New,monospace}.markdown-body pre{position:relative;line-height:1.75}.markdown-body pre>code{font-size:12px;padding:16px 12px;margin:0;word-break:normal;display:block;overflow-x:auto;color:#262626;border:1px solid #2f845e;border-top:8px solid #2f845e;background:linear-gradient(180deg,rgba(66,185,131,.1),transparent)!important}.markdown-body pre>code.hljs[lang]:before{top:8px!important;color:#2f845e!important}.markdown-body pre>code.language-awesome_error{border:1px solid #ff4d4f!important;border-left-width:8px;font-size:14px;font-weight:700;padding:15px 12px 15px 16px;margin:0;word-break:normal;white-space:break-spaces;display:block;overflow-x:auto;color:#ff4d4f!important;background:#fff2f0!important}.markdown-body pre>code.language-awesome_error:before{content:"!"!important;position:absolute!important;top:50%!important;left:-9px!important;transform:translateY(-14px)!important;background:#ff4d4f!important;color:#fff!important;border:2px solid #fff!important;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:100%;font-weight:700;font-family:Dosis,Source Sans Pro,Helvetica Neue,Arial,sans-serif;font-size:16px}.markdown-body pre>code.language-awesome_warn{border:1px solid #ffc46f!important;border-left-width:8px;font-size:14px;font-weight:700;padding:15px 12px 15px 16px;margin:0;word-break:normal;white-space:break-spaces;display:block;overflow-x:auto;color:#ffc46f!important;background:#fffbe6!important}.markdown-body pre>code.language-awesome_warn:before{content:"☂"!important;position:absolute;top:50%!important;left:-9px!important;transform:translateY(-14px)!important;background:#ffc46f!important;color:#fff!important;border:2px solid #fff!important;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:100%;font-weight:700;font-family:Dosis,Source Sans Pro,Helvetica Neue,Arial,sans-serif;font-size:16px}.markdown-body pre>code.language-awesome_success{border:1px solid #52c41a!important;border-left-width:8px;font-size:14px;font-weight:700;padding:15px 12px 15px 16px;margin:0;word-break:normal;white-space:break-spaces;display:block;overflow-x:auto;color:#52c41a!important;background:#f6ffed!important}.markdown-body pre>code.language-awesome_success:before{content:"✓"!important;position:absolute!important;top:50%!important;left:-9px!important;transform:translateY(-14px)!important;background:#52c41a!important;color:#fff!important;border:2px solid #fff!important;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:100%;font-weight:700;font-family:Dosis,Source Sans Pro,Helvetica Neue,Arial,sans-serif;font-size:16px}.markdown-body pre>code.language-awesome_info{border:1px solid #1890ff!important;border-left-width:8px;font-size:14px;font-weight:700;padding:15px 12px 15px 16px;margin:0;word-break:normal;white-space:break-spaces;display:block;overflow-x:auto;color:#1890ff!important;background:#e6f7ff!important}.markdown-body pre>code.language-awesome_info:before{content:"i"!important;position:absolute!important;top:50%!important;left:-9px!important;transform:translateY(-14px)!important;background:#1890ff!important;color:#fff!important;border:2px solid #fff!important;display:flex;align-items:center;justify-content:center;width:22px;height:22px;border-radius:100%;font-weight:700;font-family:Dosis,Source Sans Pro,Helvetica Neue,Arial,sans-serif;font-size:16px}.markdown-body strong{background-color:inherit;color:#2f845e}.markdown-body em{background-color:inherit;color:#949415}.markdown-body a{text-decoration:none;color:#2f8e54;border-bottom:1px solid #3f9e64}.markdown-body a:active,.markdown-body a:hover{color:#3f9e64}.markdown-body a[class^=footnote]{margin-left:4px}.markdown-body a:before{content:"➤ "}.markdown-body table{font-size:12px;width:100%;max-width:100%;overflow:auto;border:2px solid #2f8e54}.markdown-body thead{background:#2f8e54;color:#fff;text-align:left;font-weight:700}.markdown-body tr:nth-child(2n){background-color:rgba(153,255,188,.1)}.markdown-body td,.markdown-body th{padding:12px 7px;line-height:22px}.markdown-body td{min-width:120px}.markdown-body blockquote{padding:1px 22px;margin:22px 0;border-left:6px solid #2f845e;background-color:rgba(66,185,131,.1);border-radius:2px}.markdown-body blockquote:after{display:block;content:""}.markdown-body blockquote>p{margin:10px 0}.markdown-body ol,.markdown-body ul{padding-left:28px}.markdown-body ol li,.markdown-body ul li{margin-bottom:0;list-style:inherit}.markdown-body ol li::marker,.markdown-body ul li::marker{color:#2f845e}.markdown-body ol li .task-list-item,.markdown-body ul li .task-list-item{list-style:none}.markdown-body ol li .task-list-item ol,.markdown-body ol li .task-list-item ul,.markdown-body ul li .task-list-item ol,.markdown-body ul li .task-list-item ul{margin-top:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-top:3px}.markdown-body ol li{padding-left:6px;color:#282d36}.markdown-body del{color:#2f845e}.markdown-body input[type=checkbox]:checked:before{content:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA/klEQVQ4T72TMU7DQBBF318XdFR06egQEnAXRINEGlqgowoIR8AF4AZOZ4JEGq5AC5EixBU4A55BNrEVHAcSBTHlaubt37/zxZKlcn7n6mDPXJvz8IJ89HzWu8t7C8D2dfsY52ae4apHnLx0ktsCsHXZjiUuFgG40x2eJ/H/AhztB+zDUTpLwWj8jGkzxSHiHaMPrDQC8sMoilKzLAUqiKQjmb+ZuAdW80tmelCHODoNgSfP7AFprTTaRTzsJN1GEyuIZ7uW6TEEHwCtyV/6EVBKJHhfzgC0Xv/iXwEFBF4FG0378bd7sPQq5xK/hSnk6sdlX3mZrKkwLZKBeu8n9XuWEUE7X+YAAAAASUVORK5CYII=);position:relative;top:-1px;left:-1px}.markdown-body .math .katex{font-family:Menlo,Monaco,Consolas,Courier New,monospace;word-break:break-word;border-radius:2px;overflow-x:auto;background-color:#f6ffed;color:#52c41a;font-size:.87em;padding:.065em .4em}@media (max-width:720px){.markdown-body h1{font-size:22px}.markdown-body h2{font-size:20px}.markdown-body h3{font-size:18px}}

项目中经常用到echarts,不做封装直接拿来使用也行,但不可避免要写很多重复的配置代码,封装稍不注意又会过度封装,丢失了扩展性和可读性。始终没有找到一个好的实践,偶然看到一篇文章,给了灵感。找到了一个目前认为用起来很舒服的封装。

思路

  1. 结合项目需求,针对不同类型的图表,配置基础的默认通用配置,例如x/y,label,图例等的样式
  2. 创建图表组件实例(不要使用id,容易重复,还需要操作dom,直接用ref获取当前组件的el来创建图表),提供type(图表类型),和options(图表配置)两个必要属性
  3. 根据传入type,加载默认的图表配置
  4. 深度监听传入的options,变化时更新覆盖默认配置,更新图表
  5. 提供事件支持,支持echart事件按需绑定交互

注意要确保所有传入图表组件的options数组都是shallowReactive类型,避免数组量过大,深度响应式导致性能问题

目录结构

├─v-charts
│  │  index.ts     // 导出类型定义以及图表组件方便使用
│  │  type.d.ts    // 各种图表的类型定义
│  │  useCharts.ts // 图表hooks
│  │  v-charts.vue // echarts图表组件
│  │
│  └─options // 图表配置文件
│          bar.ts
│          gauge.ts
│          pie.ts

组件代码

v-charts.vue

<template>
  <div ref="chartRef" />
</template>
<script setup>
import { PropType } from "vue";
import * as echarts from "echarts/core";
import { useCharts, ChartType, ChartsEvents } from "./useCharts";

/**
 * echarts事件类型
 * 截至目前,vue3类型声明参数必须是以下内容之一,暂不支持外部引入类型参数
 * 1. 类型字面量
 * 2. 在同一文件中的接口或类型字面量的引用
 * // 文档中有说明:https://cn.vuejs.org/api/sfc-script-setup.html#typescript-only-features
 */
interface EventEmitsType {
  <T extends ChartsEvents.EventType>(e: `${T}`, event: ChartsEvents.Events[Uncapitalize<T>]): void;
}

defineOptions({
  name: "VCharts"
});

const props = defineProps({
  type: {
    type: String as PropType<ChartType>,
    default: "bar"
  },
  options: {
    type: Object as PropType<echarts.EChartsCoreOption>,
    default: () => ({})
  }
});

// 定义事件,提供ts支持,在组件使用时可获得友好提示
defineEmits<EventEmitsType>();

const { type, options } = toRefs(props);
const chartRef = shallowRef();
const { charts, setOptions, initChart } = useCharts({ type, el: chartRef });

onMounted(async () => {
  await initChart();
  setOptions(options.value);
});
watch(
  options,
  () => {
    setOptions(options.value);
  },
  {
    deep: true
  }
);
defineExpose({
  $charts: charts
});
</script>
<style scoped>
.v-charts {
  width: 100%;
  height: 100%;
  min-height: 200px;
}
</style>

useCharts.ts

import { ChartType } from "./type";
import * as echarts from "echarts/core";
import { ShallowRef, Ref } from "vue";

import {
  TitleComponent,
  LegendComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from "echarts/components";

import { BarChart, LineChart, PieChart, GaugeChart } from "echarts/charts";

import { LabelLayout, UniversalTransition } from "echarts/features";
import { CanvasRenderer } from "echarts/renderers";

const optionsModules = import.meta.glob<{ default: echarts.EChartsCoreOption }>("./options/**.ts");

interface ChartHookOption {
  type?: Ref<ChartType>;
  el: ShallowRef<HTMLElement>;
}

/**
 *  视口变化时echart图表自适应调整
 */
class ChartsResize {
  #charts = new Set<echarts.ECharts>(); // 缓存已经创建的图表实例
  #timeId = null;
  constructor() {
    window.addEventListener("resize", this.handleResize.bind(this)); // 视口变化时调整图表
  }
  getCharts() {
    return [...this.#charts];
  }
  handleResize() {
    clearTimeout(this.#timeId);
    this.#timeId = setTimeout(() => {
      this.#charts.forEach(chart => {
        chart.resize();
      });
    }, 500);
  }
  add(chart: echarts.ECharts) {
    this.#charts.add(chart);
  }
  remove(chart: echarts.ECharts) {
    this.#charts.delete(chart);
  }
  removeListener() {
    window.removeEventListener("resize", this.handleResize);
  }
}

export const chartsResize = new ChartsResize();

export const useCharts = ({ type, el }: ChartHookOption) => {
  echarts.use([
    BarChart,
    LineChart,
    BarChart,
    PieChart,
    GaugeChart,
    TitleComponent,
    LegendComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
  ]);
  const charts = shallowRef<echarts.ECharts>();
  let options!: echarts.EChartsCoreOption;
  const getOptions = async () => {
    const moduleKey = `./options/${type.value}.ts`;
    const { default: defaultOption } = await optionsModules[moduleKey]();
    return defaultOption;
  };

  const setOptions = (opt: echarts.EChartsCoreOption) => {
    charts.value.setOption(opt);
  };
  const initChart = async () => {
    charts.value = echarts.init(el.value);
    options = await getOptions();
    charts.value.setOption(options);
    chartsResize.add(charts.value); // 将图表实例添加到缓存中
    initEvent(); // 添加事件支持
  };

  /**
   * 初始化事件,按需绑定事件
   */
  const attrs = useAttrs();
  const initEvent = () => {
    Object.keys(attrs).forEach(attrKey => {
      if (/^on/.test(attrKey)) {
        const cb = attrs[attrKey];
        attrKey = attrKey.replace(/^on(Chart)?/, "");
        attrKey = `${attrKey[0]}${attrKey.substring(1)}`;
        typeof cb === "function" && charts.value?.on(attrKey, cb as () => void);
      }
    });
  };

  onBeforeUnmount(() => {
    chartsResize.remove(charts.value); // 移除缓存
  });

  return {
    charts,
    setOptions,
    initChart,
    initEvent
  };
};

export const chartsOptions = <T extends echarts.EChartsCoreOption>(option: T) => shallowReactive<T>(option);

export * from "./type.d";

type.d.ts

/*
 * @Description:
 * @Version: 2.0
 * @Autor: GC
 * @Date: 2022-03-02 10:21:33
 * @LastEditors: GC
 * @LastEditTime: 2022-06-02 17:45:48
 */
// import * as echarts from 'echarts/core';
import * as echarts from 'echarts'
import { XAXisComponentOption, YAXisComponentOption } from 'echarts';

import { ECElementEvent, SelectChangedPayload, HighlightPayload,  } from 'echarts/types/src/util/types'

import {
  TitleComponentOption,
  TooltipComponentOption,
  GridComponentOption,
  DatasetComponentOption,
  AriaComponentOption,
  AxisPointerComponentOption,
  LegendComponentOption,
} from 'echarts/components';// 组件
import {
  // 系列类型的定义后缀都为 SeriesOption
  BarSeriesOption,
  LineSeriesOption,
  PieSeriesOption,
  FunnelSeriesOption,
  GaugeSeriesOption
} from 'echarts/charts';

type Options = LineECOption | BarECOption | PieECOption | FunnelOption

type BaseOptionType = XAXisComponentOption | YAXisComponentOption | TitleComponentOption | TooltipComponentOption | LegendComponentOption | GridComponentOption

type BaseOption = echarts.ComposeOption<BaseOptionType>

type LineECOption = echarts.ComposeOption<LineSeriesOption | BaseOptionType>

type BarECOption = echarts.ComposeOption<BarSeriesOption | BaseOptionType>

type PieECOption = echarts.ComposeOption<PieSeriesOption | BaseOptionType>

type FunnelOption = echarts.ComposeOption<FunnelSeriesOption | BaseOptionType>

type GaugeECOption = echarts.ComposeOption<GaugeSeriesOption | GridComponentOption>

type EChartsOption = echarts.EChartsOption;

type ChartType = 'bar' | 'line' | 'pie' | 'gauge'

// echarts事件
namespace ChartsEvents {
  // 鼠标事件类型
  type MouseEventType = 'click' | 'dblclick' | 'mousedown' | 'mousemove' | 'mouseup' | 'mouseover' | 'mouseout' | 'globalout' | 'contextmenu' // 鼠标事件类型
  type MouseEvents = {
    [key in Exclude<MouseEventType,'globalout'|'contextmenu'> as `chart${Capitalize<key>}`] :ECElementEvent
  }
  // 其他的事件类型极参数
  interface Events extends MouseEvents {
    globalout:ECElementEvent,
    contextmenu:ECElementEvent,
    selectchanged: SelectChangedPayload;
    highlight: HighlightPayload;
    legendselected: { // 图例选中后的事件
      type: 'legendselected',
      // 选中的图例名称
      name: string
      // 所有图例的选中状态表
      selected: {
        [name: string]: boolean
      }
    };
    // ... 其他类型的事件在这里定义
  }


  // echarts所有的事件类型
  type EventType = keyof Events
}

export {
  BaseOption,
  ChartType,
  LineECOption,
  BarECOption,
  Options,
  PieECOption,
  FunnelOption,
  GaugeECOption,
  EChartsOption,
  ChartsEvents
}

options/bar.ts

import { BarECOption } from "../type";
const options: BarECOption = {
  legend: {},
  tooltip: {},
  xAxis: {
    type: "category",
    axisLine: {
      lineStyle: {
        // type: "dashed",
        color: "#C8D0D7"
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: "#7D8292"
    }
  },
  yAxis: {
    type: "value",
    alignTicks: true,
    splitLine: {
      show: true,
      lineStyle: {
        color: "#C8D0D7",
        type: "dashed"
      }
    },
    axisLine: {
      lineStyle: {
        color: "#7D8292"
      }
    }
  },
  grid: {
    left: 60,
    bottom: "8%",
    top: "20%"
  },
  series: [
    {
      type: "bar",
      barWidth: 20,
      itemStyle: {
        color: {
          type: "linear",
          x: 0,
          x2: 0,
          y: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "#62A5FF" // 0% 处的颜色
            },
            {
              offset: 1,
              color: "#3365FF" // 100% 处的颜色
            }
          ]
        }
      }
      // label: {
      //   show: true,
      //   position: "top"
      // }
    }
  ]
};
export default options;

项目中使用

index.vue

<template>
  <div>
    <section>
      <div class="device-statistics chart-box">
        <div>累计设备接入统计</div>
        <v-charts
          type="bar"
          :options="statisDeviceByUserObjectOpts"
          @selectchanged="selectchanged"
          @chart-click="handleChartClick"
        />
      </div>
      <div class="coordinate-statistics chart-box">
        <div>坐标数据接入统计</div>
        <v-charts type="bar" :options="statisCoordAccess" />
      </div>
    </section>
  </div>
</template>
<script setup>
import {
  useStatisDeviceByUserObject,
} from "./hooks";
// 设备分类统计
const { options: statisDeviceByUserObjectOpts,selectchanged,handleChartClick } = useStatisDeviceByUserObject();
</script>

/hooks/useStatisDeviceByUserObject.ts

export const useStatisDeviceByUserObject = () => {
  // 使用chartsOptions确保所有传入v-charts组件的options数据都是## shallowReactive浅层作用形式,避免大量数据导致性能问题
  const options = chartsOptions<BarECOption>({
    yAxis: {},
    xAxis: {},
    series: []
  });
  const init = async () => {
    const xData = [];
    const sData = [];
    const dicts = useHashMapDics<["dev_user_object"]>(["dev_user_object"]);
    const data = await statisDeviceByUserObject();
    dicts.dictionaryMap.dev_user_object.forEach(({ label, value }) => {
      if (value === "6") return; // 排除其他
      xData.push(label);
      const temp = data.find(({ name }) => name === value);
      sData.push(temp?.qty || 0);
      
      // 给options赋值时要注意options是浅层响应式
      options.xAxis = { data: xData }; 
      options.series = [{ ...options.series[0], data: sData }];
    });
  };
  
  // 事件
  const selectchanged = (params: ChartsEvents.Events["selectchanged"]) => {
    console.log(params, "选中图例了");
  };

  const handleChartClick = (params: ChartsEvents.Events["chartClick"]) => {
    console.log(params, "点击了图表");
  };
  
  onMounted(() => {
    init();
  });
  return {
    options,
    selectchanged,
    handleChartClick
  };
};

使用时输入@可以看到组件支持的所有事件:

聊聊vue3中echarts用什么形式封装最好?(代码详解)

  • 推荐学习:《vue.js视频教程》

以上就是聊聊vue3中echarts用什么形式封装最好?(代码详解)的详细内容!