Echarts官方文档https://echarts.apache.org/zh/index.html
我们日常使用echarts时,常用步骤为:
npm下载echarts包 -> 全部引入echarts -> 使用
可优化的地方就是引入echarts这里,官方文档里提供了两种引入方式:1、全部引入;2、按需引入。
echarts有很多种图表类型,我相信大部分项目都只是用到某几种图表,如果我们全部引入,打包时会导致echarts约几MB,但如果我们按需引入用到的图表,那打包后的echarts包大小就是按KB为单位的。
全部引入:
import * as echarts from 'echarts';
按需引入:
vue2:
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from 'echarts/core';
// 引入柱状图图表,图表后缀都为 Chart
import { BarChart } from 'echarts/charts';
// 引入标题,提示框,直角坐标系,数据集,内置数据转换器组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 SVG 渲染器 (!!!SVG的渲染性能比Canvas好)
import { SVGRenderer } from 'echarts/renderers';
// 注册必须的组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
BarChart,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);
// 接下来的使用就跟之前一样,初始化图表,设置配置项
var myChart = echarts.init(document.getElementById('main'));
myChart.setOption({
// ...
});
vue3:
import * as echarts from 'echarts/core';
import {
BarChart,
LineChart
} from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
GridComponent,
// 数据集组件
DatasetComponent,
// 内置数据转换器组件 (filter, sort)
TransformComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { SVGRenderer } from 'echarts/renderers';
import type {
// 系列类型的定义后缀都为 SeriesOption
BarSeriesOption,
LineSeriesOption
} from 'echarts/charts';
import type {
// 组件类型的定义后缀都为 ComponentOption
TitleComponentOption,
TooltipComponentOption,
GridComponentOption,
DatasetComponentOption
} from 'echarts/components';
import type {
ComposeOption,
} from 'echarts/core';
// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = ComposeOption<
| BarSeriesOption
| LineSeriesOption
| TitleComponentOption
| TooltipComponentOption
| GridComponentOption
| DatasetComponentOption
>;
// 注册必须的组件
echarts.use([
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
BarChart,
LineChart,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);
const option: ECOption = {
// ...
};
!注意:
上述代码中,与echarts示例不同的是 import { SVGRenderer } from 'echarts/renderers';
我使用了SVG渲染器,因为SVG的渲染性能比Canvas的渲染性能要好,如果你的项目不需要什么非常复杂的渲染效果,推荐SVG渲染器。
除了示例里面的图表类型,我们应该还会用到其他类型,那么问题来了:用到其他图表时,我该怎么知道这个类型的图表在echarts内容叫啥名呢?
我自己都是先直接在option中使用,页面控制台会错,然后再去初始化echarts文件中引入。
比如我想使用盒形图(Boxplot),但不知道盒形图在echarts内部的命名,所以无法引入。那我就先在option中使用盒形图,然后看控制台的报错:
看到这个BoxplotChart了,我再去引入
import{
...,
BoxplotChart,
type BoxplotSeriesOption,
...
} from 'echarts/charts';
export type ECOption = echarts.ComposeOption<
...,
| BoxplotSeriesOption,
...
>
echarts.use([
...,
BoxplotChart,
...
])