优雅封装echarts

97 阅读1分钟

未封装之前,一个图表一个组件,看了里面的代码,除了data和options不一致,其他代码都是可以复用的,就想着去封装一下

image.png

这是封装之后的代码

image.png

看一下index.ts文件

image.png 使用的是函数根据data返回一个配置项,返回的配置项有点多就展开其中一个进行展示

code.png

charts.vue代码也是比较简单

<template>
  <div class="com-container">
    <div class="com-chart" ref="chartsRef"></div>
  </div>
</template>

<script lang="ts" setup>
import useGlobal from '@/views/hooks/useGlobal';
import { ref, onMounted, onBeforeUnmount, watch, defineProps } from 'vue';
const global = useGlobal();
const props = withDefaults(
  defineProps<{
    data: Array<string>;
    chartOptions: object;
  }>(),
  {
    data: () => []
  }
);
const chartsRef = ref<HTMLDivElement | null>(null);

const initChart = () => {
  const histogram = global.$echarts.init(chartsRef.value);
  // 工厂函数进行返回配置项
  const options = props.chartOptions(props.data);
  histogram.setOption(options);
  window.addEventListener('resize', handleWindowResize);
  return histogram;
};

const handleWindowResize = () => {
  if (!chartsRef.value) return;
  initChart().resize();
};

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleWindowResize);
});
//监听数据,有数据就更新echarts
watch(
  () => props.data,
  () => {
    if (props.data) {
      console.log(
        '🚀 ~ file: charts.vue:46 ~ props.chartOptions:',
        props.chartOptions
      );
      initChart();
    }
  }
);
</script>

<style scoped>
.com-container {
  width: 100%;
  height: 25vw;
  background-color: var(--bg-color);
  padding: 15px;
}

.com-chart {
  width: 100%;
  height: 100%;
}
</style>

使用也比较简单

<div class="echart_box flex flex-wrap">
   <Charts :data="monthData" :chart-options='monthOptions' />
  <Charts :data="fakeData" :chart-options='ageOptions' />
  <Map :userData="userData" />
  <Charts :data="genderData" :chart-options='genderOptions' />
</div>

// 导入组件和函数
import Charts from './components/charts.vue';
import { ageOptions, monthOptions, genderOptions } from './components';
 

相比较之前的代码,使用起来更加优雅,配置新的图标,只需要去配置options,用过echarts官网的代码示例就知道,可以直接复制配置代码,开发效率一下子就上去了