聊聊vue3中echarts用什么形式封装最好

 3166

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

思路

结合项目需求,针对不同类型的图表,配置基础的默认通用配置,例如x/y,label,图例等的样式

创建图表组件实例(不要使用id,容易重复,还需要操作dom,直接用ref获取当前组件的el来创建图表),提供type(图表类型),和options(图表配置)两个必要属性

根据传入type,加载默认的图表配置

深度监听传入的options,变化时更新覆盖默认配置,更新图表

提供事件支持,支持echart事件按需绑定交互

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


目录结构

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


组件代码

v-charts.vue

  1. <template>
  2.   <div ref="chartRef" />
  3. </template>
  4. <script setup>
  5. import { PropType } from "vue";
  6. import * as echarts from "echarts/core";
  7. import { useCharts, ChartType, ChartsEvents } from "./useCharts";
  8.  
  9. /**
  10.  * echarts事件类型
  11.  * 截至目前,vue3类型声明参数必须是以下内容之一,暂不支持外部引入类型参数
  12.  * 1. 类型字面量
  13.  * 2. 在同一文件中的接口或类型字面量的引用
  14.  * // 文档中有说明:https://cn.vuejs.org/api/sfc-script-setup.html#typescript-only-features
  15.  */
  16. interface EventEmitsType {
  17.   <T extends ChartsEvents.EventType>(e: `${T}`, event: ChartsEvents.Events[Uncapitalize<T>]): void;
  18. }
  19.  
  20. defineOptions({
  21.   name: "VCharts"
  22. });
  23.  
  24. const props = defineProps({
  25.   type: {
  26.     type: String as PropType<ChartType>,
  27.     default: "bar"
  28.   },
  29.   options: {
  30.     type: Object as PropType<echarts.EChartsCoreOption>,
  31.     default: () => ({})
  32.   }
  33. });
  34.  
  35. // 定义事件,提供ts支持,在组件使用时可获得友好提示
  36. defineEmits<EventEmitsType>();
  37.  
  38. const { type, options } = toRefs(props);
  39. const chartRef = shallowRef();
  40. const { charts, setOptions, initChart } = useCharts({ type, el: chartRef });
  41.  
  42. onMounted(async () => {
  43.   await initChart();
  44.   setOptions(options.value);
  45. });
  46. watch(
  47.   options,
  48.   () => {
  49.     setOptions(options.value);
  50.   },
  51.   {
  52.     deep: true
  53.   }
  54. );
  55. defineExpose({
  56.   $charts: charts
  57. });
  58. </script>
  59. <style scoped>
  60. .v-charts {
  61.   width: 100%;
  62.   height: 100%;
  63.   min-height: 200px;
  64. }
  65. </style>


useCharts.ts

  1. import { ChartType } from "./type";
  2. import * as echarts from "echarts/core";
  3. import { ShallowRef, Ref } from "vue";
  4.  
  5. import {
  6.   TitleComponent,
  7.   LegendComponent,
  8.   TooltipComponent,
  9.   GridComponent,
  10.   DatasetComponent,
  11.   TransformComponent
  12. } from "echarts/components";
  13.  
  14. import { BarChart, LineChart, PieChart, GaugeChart } from "echarts/charts";
  15.  
  16. import { LabelLayout, UniversalTransition } from "echarts/features";
  17. import { CanvasRenderer } from "echarts/renderers";
  18.  
  19. const optionsModules = import.meta.glob<{ default: echarts.EChartsCoreOption }>("./options/**.ts");
  20.  
  21. interface ChartHookOption {
  22.   type?: Ref<ChartType>;
  23.   el: ShallowRef<HTMLElement>;
  24. }
  25.  
  26. /**
  27.  *  视口变化时echart图表自适应调整
  28.  */
  29. class ChartsResize {
  30.   #charts = new Set<echarts.ECharts>(); // 缓存已经创建的图表实例
  31.   #timeId = null;
  32.   constructor() {
  33.     window.addEventListener("resize", this.handleResize.bind(this)); // 视口变化时调整图表
  34.   }
  35.   getCharts() {
  36.     return [...this.#charts];
  37.   }
  38.   handleResize() {
  39.     clearTimeout(this.#timeId);
  40.     this.#timeId = setTimeout(() => {
  41.       this.#charts.forEach(chart => {
  42.         chart.resize();
  43.       });
  44.     }, 500);
  45.   }
  46.   add(chart: echarts.ECharts) {
  47.     this.#charts.add(chart);
  48.   }
  49.   remove(chart: echarts.ECharts) {
  50.     this.#charts.delete(chart);
  51.   }
  52.   removeListener() {
  53.     window.removeEventListener("resize", this.handleResize);
  54.   }
  55. }
  56.  
  57. export const chartsResize = new ChartsResize();
  58.  
  59. export const useCharts = ({ type, el }: ChartHookOption) => {
  60.   echarts.use([
  61.     BarChart,
  62.     LineChart,
  63.     BarChart,
  64.     PieChart,
  65.     GaugeChart,
  66.     TitleComponent,
  67.     LegendComponent,
  68.     TooltipComponent,
  69.     GridComponent,
  70.     DatasetComponent,
  71.     TransformComponent,
  72.     LabelLayout,
  73.     UniversalTransition,
  74.     CanvasRenderer
  75.   ]);
  76.   const charts = shallowRef<echarts.ECharts>();
  77.   let options!: echarts.EChartsCoreOption;
  78.   const getOptions = async () => {
  79.     const moduleKey = `./options/${type.value}.ts`;
  80.     const { default: defaultOption } = await optionsModules[moduleKey]();
  81.     return defaultOption;
  82.   };
  83.  
  84.   const setOptions = (opt: echarts.EChartsCoreOption) => {
  85.     charts.value.setOption(opt);
  86.   };
  87.   const initChart = async () => {
  88.     charts.value = echarts.init(el.value);
  89.     options = await getOptions();
  90.     charts.value.setOption(options);
  91.     chartsResize.add(charts.value); // 将图表实例添加到缓存中
  92.     initEvent(); // 添加事件支持
  93.   };
  94.  
  95.   /**
  96.    * 初始化事件,按需绑定事件
  97.    */
  98.   const attrs = useAttrs();
  99.   const initEvent = () => {
  100.     Object.keys(attrs).forEach(attrKey => {
  101.       if (/^on/.test(attrKey)) {
  102.         const cb = attrs[attrKey];
  103.         attrKey = attrKey.replace(/^on(Chart)?/, "");
  104.         attrKey = `${attrKey[0]}${attrKey.substring(1)}`;
  105.         typeof cb === "function" && charts.value?.on(attrKey, cb as () => void);
  106.       }
  107.     });
  108.   };
  109.  
  110.   onBeforeUnmount(() => {
  111.     chartsResize.remove(charts.value); // 移除缓存
  112.   });
  113.  
  114.   return {
  115.     charts,
  116.     setOptions,
  117.     initChart,
  118.     initEvent
  119.   };
  120. };
  121.  
  122. export const chartsOptions = <T extends echarts.EChartsCoreOption>(option: T) => shallowReactive<T>(option);
  123.  
  124. export * from "./type.d";


type.d.ts

  1. /*
  2.  * @Description:
  3.  * @Version: 2.0
  4.  * @Autor: GC
  5.  * @Date: 2022-03-02 10:21:33
  6.  * @LastEditors: GC
  7.  * @LastEditTime: 2022-06-02 17:45:48
  8.  */
  9. // import * as echarts from 'echarts/core';
  10. import * as echarts from 'echarts'
  11. import { XAXisComponentOption, YAXisComponentOption } from 'echarts';
  12.  
  13. import { ECElementEvent, SelectChangedPayload, HighlightPayload,  } from 'echarts/types/src/util/types'
  14.  
  15. import {
  16.   TitleComponentOption,
  17.   TooltipComponentOption,
  18.   GridComponentOption,
  19.   DatasetComponentOption,
  20.   AriaComponentOption,
  21.   AxisPointerComponentOption,
  22.   LegendComponentOption,
  23. } from 'echarts/components';// 组件
  24. import {
  25.   // 系列类型的定义后缀都为 SeriesOption
  26.   BarSeriesOption,
  27.   LineSeriesOption,
  28.   PieSeriesOption,
  29.   FunnelSeriesOption,
  30.   GaugeSeriesOption
  31. } from 'echarts/charts';
  32.  
  33. type Options = LineECOption | BarECOption | PieECOption | FunnelOption
  34.  
  35. type BaseOptionType = XAXisComponentOption | YAXisComponentOption | TitleComponentOption | TooltipComponentOption | LegendComponentOption | GridComponentOption
  36.  
  37. type BaseOption = echarts.ComposeOption<BaseOptionType>
  38.  
  39. type LineECOption = echarts.ComposeOption<LineSeriesOption | BaseOptionType>
  40.  
  41. type BarECOption = echarts.ComposeOption<BarSeriesOption | BaseOptionType>
  42.  
  43. type PieECOption = echarts.ComposeOption<PieSeriesOption | BaseOptionType>
  44.  
  45. type FunnelOption = echarts.ComposeOption<FunnelSeriesOption | BaseOptionType>
  46.  
  47. type GaugeECOption = echarts.ComposeOption<GaugeSeriesOption | GridComponentOption>
  48.  
  49. type EChartsOption = echarts.EChartsOption;
  50.  
  51. type ChartType = 'bar' | 'line' | 'pie' | 'gauge'
  52.  
  53. // echarts事件
  54. namespace ChartsEvents {
  55.   // 鼠标事件类型
  56.   type MouseEventType = 'click' | 'dblclick' | 'mousedown' | 'mousemove' | 'mouseup' | 'mouseover' | 'mouseout' | 'globalout' | 'contextmenu' // 鼠标事件类型
  57.   type MouseEvents = {
  58.     [key in Exclude<MouseEventType,'globalout'|'contextmenu'> as `chart${Capitalize<key>}`] :ECElementEvent
  59.   }
  60.   // 其他的事件类型极参数
  61.   interface Events extends MouseEvents {
  62.     globalout:ECElementEvent,
  63.     contextmenu:ECElementEvent,
  64.     selectchanged: SelectChangedPayload;
  65.     highlight: HighlightPayload;
  66.     legendselected: { // 图例选中后的事件
  67.       type: 'legendselected',
  68.       // 选中的图例名称
  69.       name: string
  70.       // 所有图例的选中状态表
  71.       selected: {
  72.         [name: string]: boolean
  73.       }
  74.     };
  75.     // ... 其他类型的事件在这里定义
  76.   }
  77.  
  78.  
  79.   // echarts所有的事件类型
  80.   type EventType = keyof Events
  81. }
  82.  
  83. export {
  84.   BaseOption,
  85.   ChartType,
  86.   LineECOption,
  87.   BarECOption,
  88.   Options,
  89.   PieECOption,
  90.   FunnelOption,
  91.   GaugeECOption,
  92.   EChartsOption,
  93.   ChartsEvents
  94. }


options/bar.ts

  1. import { BarECOption } from "../type";
  2. const options: BarECOption = {
  3.   legend: {},
  4.   tooltip: {},
  5.   xAxis: {
  6.     type: "category",
  7.     axisLine: {
  8.       lineStyle: {
  9.         // type: "dashed",
  10.         color: "#C8D0D7"
  11.       }
  12.     },
  13.     axisTick: {
  14.       show: false
  15.     },
  16.     axisLabel: {
  17.       color: "#7D8292"
  18.     }
  19.   },
  20.   yAxis: {
  21.     type: "value",
  22.     alignTicks: true,
  23.     splitLine: {
  24.       show: true,
  25.       lineStyle: {
  26.         color: "#C8D0D7",
  27.         type: "dashed"
  28.       }
  29.     },
  30.     axisLine: {
  31.       lineStyle: {
  32.         color: "#7D8292"
  33.       }
  34.     }
  35.   },
  36.   grid: {
  37.     left: 60,
  38.     bottom: "8%",
  39.     top: "20%"
  40.   },
  41.   series: [
  42.     {
  43.       type: "bar",
  44.       barWidth: 20,
  45.       itemStyle: {
  46.         color: {
  47.           type: "linear",
  48.           x: 0,
  49.           x2: 0,
  50.           y: 0,
  51.           y2: 1,
  52.           colorStops: [
  53.             {
  54.               offset: 0,
  55.               color: "#62A5FF" // 0% 处的颜色
  56.             },
  57.             {
  58.               offset: 1,
  59.               color: "#3365FF" // 100% 处的颜色
  60.             }
  61.           ]
  62.         }
  63.       }
  64.       // label: {
  65.       //   show: true,
  66.       //   position: "top"
  67.       // }
  68.     }
  69.   ]
  70. };
  71. export default options;


项目中使用

index.vue

  1. <template>
  2.   <div>
  3.     <section>
  4.       <div class="device-statistics chart-box">
  5.         <div>累计设备接入统计</div>
  6.         <v-charts
  7.           type="bar"
  8.           :options="statisDeviceByUserObjectOpts"
  9.           @selectchanged="selectchanged"
  10.           @chart-click="handleChartClick"
  11.         />
  12.       </div>
  13.       <div class="coordinate-statistics chart-box">
  14.         <div>坐标数据接入统计</div>
  15.         <v-charts type="bar" :options="statisCoordAccess" />
  16.       </div>
  17.     </section>
  18.   </div>
  19. </template>
  20. <script setup>
  21. import {
  22.   useStatisDeviceByUserObject,
  23. } from "./hooks";
  24. // 设备分类统计
  25. const { options: statisDeviceByUserObjectOpts,selectchanged,handleChartClick } = useStatisDeviceByUserObject();
  26. </script>


/hooks/useStatisDeviceByUserObject.ts

  1. export const useStatisDeviceByUserObject = () => {
  2.   // 使用chartsOptions确保所有传入v-charts组件的options数据都是## shallowReactive浅层作用形式,避免大量数据导致性能问题
  3.   const options = chartsOptions<BarECOption>({
  4.     yAxis: {},
  5.     xAxis: {},
  6.     series: []
  7.   });
  8.   const init = async () => {
  9.     const xData = [];
  10.     const sData = [];
  11.     const dicts = useHashMapDics<["dev_user_object"]>(["dev_user_object"]);
  12.     const data = await statisDeviceByUserObject();
  13.     dicts.dictionaryMap.dev_user_object.forEach(({ label, value }) => {
  14.       if (value === "6") return; // 排除其他
  15.       xData.push(label);
  16.       const temp = data.find(({ name }) => name === value);
  17.       sData.push(temp?.qty || 0);
  18.        
  19.       // 给options赋值时要注意options是浅层响应式
  20.       options.xAxis = { data: xData }; 
  21.       options.series = [{ ...options.series[0], data: sData }];
  22.     });
  23.   };
  24.    
  25.   // 事件
  26.   const selectchanged = (params: ChartsEvents.Events["selectchanged"]) => {
  27.     console.log(params, "选中图例了");
  28.   };
  29.  
  30.   const handleChartClick = (params: ChartsEvents.Events["chartClick"]) => {
  31.     console.log(params, "点击了图表");
  32.   };
  33.    
  34.   onMounted(() => {
  35.     init();
  36.   });
  37.   return {
  38.     options
  39.     selectchanged,
  40.     handleChartClick
  41.   };
  42. };


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


聊聊vue3中echarts用什么形式封装最好

TAG标签:
本文网址:https://www.zztuku.com/index.php/detail-13839.html
站长图库 - 聊聊vue3中echarts用什么形式封装最好
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐

    漂亮的销售标签矢量素材