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>
相关推荐
Lovely Ruby10 分钟前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·学习·golang
老华带你飞11 分钟前
健身房|基于springboot + vue健身房管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
JIngJaneIL15 分钟前
基于Java酒店预约系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
深红18 分钟前
玩转小程序AR-实战篇
前端·微信小程序·webvr
银空飞羽18 分钟前
让Trae SOLO全自主学习开发近期爆出的React RCE漏洞靶场并自主利用验证(CVE-2025-55182)
前端·人工智能·安全
钮钴禄·爱因斯晨29 分钟前
DevUI 组件生态与 MateChat 智能应用:企业级前端智能化实战
前端
不会写DN1 小时前
存储管理在开发中有哪些应用?
前端·后端
清风细雨_林木木1 小时前
Obsidian 笔试环境配置与使用指南
前端
用户47949283569152 小时前
Vite8来啦,告别 esbuild + Rollup,Vite 8 统一用 Rolldown 了
前端·javascript·vite