亲宝软件园·资讯

展开

vue3封装echarts组件最佳形式详解

远山无期 人气:0

思路

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

注意要确保所有传入图表组件的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 class="v-charts" ref="chartRef" />
</template>
<script lang="ts" setup>
import { PropType } from "vue";
import * as echarts from "echarts/core";
import { useCharts, ChartType } from "./useCharts";
defineOptions({
  name: "VCharts"
});
const props = defineProps({
  type: {
    type: String as PropType<ChartType>,
    default: "bar"
  },
  options: {
    type: Object as PropType<echarts.EChartsCoreOption>,
    default: () => ({})
  }
});
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的数据都要是shallowReactive类型,避免不必要的响应式转换
  options,
  () => {
    setOptions(options.value);
  },
  {
    deep: true
  }
);
defineExpose({
  $charts: charts
});
</script>
<style lang="scss" 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";
// 异步导入options中的所有默认配置项
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();
// 注册创建echarts实例
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); // 将图表实例添加到缓存中
  };
  onBeforeUnmount(() => {
    chartsResize.remove(charts.value); // 移除缓存
  });
  return {
    charts,
    setOptions,
    initChart
  };
};
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: GUOCHAO82
 * @LastEditTime: 2022-06-02 17:45:48
 */
// import * as echarts from 'echarts/core';
import * as echarts from 'echarts'
import { XAXisComponentOption, YAXisComponentOption } from 'echarts';
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'
export {
    BaseOption,
    ChartType,
    LineECOption, //
    BarECOption,
    Options,
    PieECOption,
    FunnelOption,
    GaugeECOption,
    EChartsOption
}

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",
    min: "dataMin",
    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 class="home">
    <section class="bottom">
      <div class="device-statistics chart-box">
        <div class="title">累计设备接入统计</div>
        <v-charts type="bar" :options="statisDeviceAccess" />
      </div>
      <div class="coordinate-statistics chart-box">
        <div class="title">坐标数据接入统计</div>
        <v-charts type="bar" :options="statisCoordAccess" />
      </div>
    </section>
  </div>
</template>
<script lang="ts" setup>
import {
  useStatisDeviceByUserObject,
} from "./hooks";
// 设备分类统计
const { options: statisDeviceByUserObjectOpts } = 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 }];
    });
  };
  onMounted(() => {
    init();
  });
  return {
    options
  };
};

加载全部内容

相关教程
猜你喜欢
用户评论