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>
相关推荐
再吃一根胡萝卜7 小时前
从零实现 DSH 用户信息插件
前端
stormsha7 小时前
我的抓取脚本凭什么从不抢你的鼠标
前端·chrome
verohh7 小时前
尾言:关于前端工程架构设计的一些思考
前端
SameX7 小时前
HarmonyOS ArkTS 做 MBTI 风格 16 人格测评用 4 维签名字符串做分类的最小算法
前端
MiniToolDesk7 小时前
告别前端运行时 undefined:用 Zod 打造端到端类型守卫(附 JSON 一键生成实战)
前端
椒哥7 小时前
伪造一份"浏览器身份证":sdenv 是怎么骗过环境检测的
前端
斯维赤7 小时前
三级缓存为什么是三级?二级缓存不够吗
前端·后端·面试
锋行天下8 小时前
LangGraph 对接 MCP 实战指南:从本地开发到线上部署与模型防坑
前端·人工智能·后端
Highcharts.js8 小时前
Highcharts与TypeScript集成指南
前端·javascript·typescript·前端框架·数据可视化·highcharts
跳跳的小古风9 小时前
前端转全栈:一条接口从前端请求到 SQL 完整流程
java·前端