vue3 封装一个通用echarts组件

实现这个组件需要引入echarts和vue-echarts插件,使用vue-echarts是因为它帮我们封装了一些很常用的功能,比如监听页面resize后重新渲染功能,本次组件只使用到了autoresize配置,其它可以根据官方文档按需选配

https://github.com/ecomfe/vue-echarts

首先引入echarts和vue-echarts插件

复制代码
npm install echarts vue-echarts -S

组件定义参数如下

TypeScript 复制代码
import type { ECBasicOption } from 'echarts/types/dist/shared'

const props = defineProps({
  // echarts options 传参
  option: {
    type: Object as PropType<ECBasicOption>,
    required: true,
  },
  // 容器宽度
  width: {
    type: String,
    default: '100%',
  },
  // 容器高度
  height: {
    type: String,
    default: '400px',
  },
})

组件代码如下

TypeScript 复制代码
<script setup lang="ts">
import { PropType, provide } from 'vue'
import type { ECBasicOption } from 'echarts/types/dist/shared'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'

// 按需引入
import { PieChart, LineChart, FunnelChart, CustomChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  ToolboxComponent,
} from 'echarts/components'

import VChart, { THEME_KEY } from 'vue-echarts'
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LineChart,
  ToolboxComponent,
  FunnelChart,
  CustomChart,
])

// 传入主题
provide(THEME_KEY, 'light')

const props = defineProps({
  option: {
    type: Object as PropType<ECBasicOption>,
    required: true,
  },
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '400px',
  },
})
</script>

<template>
  <div class="chart-container" :style="{ width, height }">
    <VChart class="w-full h-full" :option="props.option" autoresize />
  </div>
</template>
相关推荐
斌味代码2 分钟前
jQuery 内存泄漏排查:常见场景、工具使用与修复实战
前端·javascript·jquery
weixin1997010801610 分钟前
《爱回收商品详情页前端性能优化实战》
前端·性能优化
chenbin___23 分钟前
鸿蒙(HarmonyOS)支持 useNativeDriver的详细说明(转自千问)
前端·javascript·react native·react.js·harmonyos
We་ct23 分钟前
Git 核心知识点全解析
开发语言·前端·git·gitee·github
小兵阿飞31 分钟前
Vite 技术介绍:实现原理、应用与优化
前端·vite
码喽7号41 分钟前
vue学习六:状态管理VueX
javascript·vue.js·学习
jiayong2341 分钟前
第 13 课:分页、页码状态和 URL 同步
开发语言·前端·javascript·vue.js·学习
smilejingwei1 小时前
用 AI 编程生成 ECharts 图表并嵌入报表的实践
前端·人工智能·echarts·bi·报表工具·商业智能
丷丩1 小时前
第3篇:技术拆解|3dtubetilecreater 前后端架构全解析(Vue+Express+PostGIS)
vue.js·3d·架构
Linux运维技术栈2 小时前
Cloudflare Argo Smart Routing全球加速:优化跨境回源链路,提升跨区域访问体验
大数据·前端·数据库