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>
相关推荐
麦麦在写代码3 分钟前
前端学习1
前端·学习
sg_knight7 分钟前
微信小程序中 WebView 组件的使用与应用场景
前端·javascript·微信·微信小程序·小程序·web·weapp
凯子坚持 c1 小时前
生产级 Rust Web 应用架构:使用 Axum 实现模块化设计与健壮的错误处理
前端·架构·rust
IT_陈寒1 小时前
Python 3.12新特性实战:5个让你的代码效率翻倍的隐藏技巧!
前端·人工智能·后端
程序员小寒1 小时前
前端高频面试题之Vuex篇
前端·javascript·面试
网硕互联的小客服1 小时前
如何解决 Linux 文件系统挂载失败的问题?
linux·服务器·前端·网络·chrome
程序员爱钓鱼2 小时前
Python 编程实战 · 实用工具与库 — Flask 路由与模板
前端·后端·python
JIngJaneIL2 小时前
旅游|内蒙古景点旅游|基于Springboot+Vue的内蒙古景点旅游管理系统设计与实现(源码+数据库+文档)
java·vue.js·spring boot·论文·旅游·毕设·内蒙古景点旅游
麦麦大数据4 小时前
D038 vue+django西游记问答知识图谱可视化系统
vue.js·django·问答系统·知识图谱·neo4j·可视化·可是还
合作小小程序员小小店5 小时前
web开发,在线%超市销售%管理系统,基于idea,html,jsp,java,ssh,sql server数据库。
java·前端·sqlserver·ssh·intellij-idea