Vue3 + ECharts 的使用

前言

坦白说,可能有些难以置信,我花了将近半个月的时间专注于前端开发。我的主要技术栈包括 TypeScript、Vue3、Element-Plus 和 ECharts,用这一套技术搭建了一个数据展示后台。ECharts提供的图表实在是太引人注目了,几乎可以满足所有常见的数据展示场景。本文旨在记录我是如何将 ECharts 与 Vue3 结合部署和简单使用的。

安装

pnpm install echarts vue-echarts

代码编写

初始化组件

在 src 目录创建个 common 目录用于存放一些共用的库,然后新建 echarts.ts 文件,代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import * as echarts from "echarts/core";
 
import { BarChart, LineChart } from "echarts/charts";
 
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  ToolboxComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  VisualMapComponent,
  DataZoomComponent
} from "echarts/components";

 
import { LabelLayout, UniversalTransition } from "echarts/features";
 
import { CanvasRenderer } from "echarts/renderers";
 
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LineChart,
  ToolboxComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent,
  VisualMapComponent,
  DataZoomComponent
]);
 
export default echarts;

参考以上这份代码,自己调整或增加相关的图表和组件。

main.ts 程序修改

1
2
3
4
5
import echarts from './common/echarts'

const app = createApp(App)

app.config.globalProperties.$echarts = echarts;

Vue3组件里使用

定义个 div
1
<div style="margin-top: 10px; width:100%; height: 85vh;" id="chart" />
初始化及配置数据
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const internalInstance = getCurrentInstance()
const echarts = internalInstance?.appContext.config.globalProperties.$echarts

// 初始化
chart = echarts.init(document.getElementById("chart"))
window.addEventListener("resize", function () {
	chart.resize()
})


// 获取配置的数据
optionData.value = getOption()

// 设置配置数据及显示图表
chart.setOption(optionData.value, true)
0%