基于Echarts进行图表组件的封装

什么是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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值