项目中经常用到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
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 {
}
defineOptions({name: "VCharts"
});
const props = defineProps({type: {type: String as PropType
});
// 定义事件,提供ts支持,在组件使用时可获得友好提示
defineEmits
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
});
.v-charts {width: 100%;height: 100%;min-height: 200px;
}
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
}
/**
*视口变化时echart图表自适应调整
*/
class ChartsResize {#charts = new Set
}
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
};
export const chartsOptions =
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 {// 系列类型的定义后缀都为 SeriesOptionBarSeriesOption,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
type LineECOption = echarts.ComposeOption
type BarECOption = echarts.ComposeOption
type PieECOption = echarts.ComposeOption
type FunnelOption = echarts.ComposeOption
type GaugeECOption = echarts.ComposeOption
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
}
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
/hooks/useStatisDeviceByUserObject.ts
export const useStatisDeviceByUserObject = () => {// 使用chartsOptions确保所有传入v-charts组件的options数据都是## shallowReactive浅层作用形式,避免大量数据导致性能问题const options = chartsOptions
};
使用时输入@可以看到组件支持的所有事件:
最后
最近还整理一份JavaScript与ES的笔记,一共25个重要的知识点,对每个知识点都进行了讲解和分析。能帮你快速掌握JavaScript与ES的相关知识,提升工作效率。
有需要的小伙伴,可以点击下方卡片领取,无偿分享
参考文章
发表评论