什么是Echarts
是一个使用js实现的开源可视库,提供了多种图表,但是当我们在项目中进行使用的时候可能就是需要进行一系列的相关配置如: 标题,类型,x轴,y轴等,当我们使用较为频繁的时候就容易导致代码的冗余,并且整体将echarts进行安装引入也是比较大的,我们可以按照自己的需要进行对应组件的引入
Echarts的使用
安装Echarts
Echarts官网-安装echarst并实现按需引入Echarts图表和组件
基于Echarts相关配置进行组件的封装
// components/BarChart.vue
/* @/components/BarChart.vue */
<template>
<div ref="chartDom" :style="{ height: getHeight }"></div>
</template>
<script setup lang="ts">
import {
echarts, type ECOption } from '@/utils/echarts'
import {
ref, shallowRef, watch, computed, onMounted, onBeforeUnmount, type ShallowRef, type Ref } from 'vue'
import type {
EChartsType } from 'echarts/types/dist/core'
import type {
XAXisOption, YAXisOption, LegendComponentOption, BarSeriesOption, DataZoomComponentOption
} from 'echarts/types/dist/shared'
import resize from '@/utils/resize'
import type {
ChartSetting } from '@/types/ChartData'
//定义组件属性
const props = withDefaults(
defineProps<{
//数据
data?: Array<string | number>
//x轴数据
xAxisData?: Array<string>
//图表标题
title?: string
//系列配置
series?: Array<BarSeriesOption>
//x轴配置
xAxis?: Array<XAXisOption>
//y轴配置
yAxis?: Array<YAXisOption>
//图例配置
legend?: LegendComponentOption
//区域缩放配置
dataZoom?: Array<DataZoomComponentOption>
//图形高度
height?: number | string
//数据集
datasetSource?: Array<any>
//综合配置
options: ChartSetting
}>(),
{
data: () => [],
xAxisData: () => [],
title: 'ECharts柱状图',
}
)
//要渲染的Dom元素
const chartDom: Ref<HTMLDivElement | null> = ref(null)
//渲染的chart对象要用shallowRef
const chart: ShallowRef<EChartsType | null | undefined> = shallowRef(null)
//高度同时支持string和number
const getHeight = computed(() => {
return typeof props.height === 'number' ? props.height + 'px' : props.height
})
//监听数据变化,重新绘制
watch(
() => props,
() => {
drawChart()
},
{
deep: true }
)
//绘制
async function drawChart() {
let datasetSource: Array<any> | undefined = props.datasetSource,
series: Array<BarSeriesOption> = [],
xAxisData: Array<string> = props.xAxisData
let chartType = props.options.chartType || 'bar'; // 默认为柱状图,如果需要折线图则设置为 'line'
if (props.options) {
if (props.options.apiMethod) {
//获取接口数据作为数据集
let allx = await props.options.apiMethod()
datasetSource = allx.data
if (props.options.xProp) {
//根据配置的x轴属性名生成x轴数据
xAxisData = []
datasetSource?.forEach(data => {
xAxisData.push