EChart是一个非常优秀的开源前端图表库,其文档库也非常详细。但是苦于中文文档零碎(说的就是CSDN),加上版本迭代迅速,在Vue框架下引入Echarts可能会出现不少问题,本文就部分错误进行记录。

在本文中,所使用的Vue框架版本为2.6.14,ECharts版本为5.2.2,包管理器为Yarn。

使用vue-echarts

vue-echarts相当于在Vue框架下对ECharts进行了包装,对于大多数项目开发而言是一个非常不错的选择,其中文文档见:https://github.com/ecomfe/vue-echarts/blob/main/README.zh-Hans.md

我们需要在管理器中安装它:

npm install echarts vue-echarts

yarn add echarts vue-echarts

注意官网中提到的——要在 Vue 2下使用 vue-echarts,需要确保 @vue/composition-api 已经安装

main.js中我们可以对vue-echarts进行全局组件注册,或者需要的组件中进行单组件注册,具体的操作可以参照上述所提官方中文文档,这里不再赘述。

使用echarts

对于不熟悉Vue框架,或者需要使用ECharts库中更加高阶功能的开发者,似乎使用vue-echarts显得有些累赘,我们也可以直接使用echarts库。

同样,安装echarts库:

npm install echarts

yarn add echarts

但需要注意的是,从ECharts 5开始,即取消了export default的支持,我们不能直接引入echarts并设置Vue原型。

import echarts from 'echarts';
Vue.prototype.$echarts = echarts;
// No longer support!!!

一种可行的做法是,在单文件中按需引入所需模块。

新建utils/echarts.js

import * as echarts from "echarts/core";
// 核心库,必须引入并导出
import { MapChart, GaugeChart, LineChart } from "echarts/charts";
// 按需引入各图表
import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    VisualMapComponent
} from "echarts/components";
// 按需引入各图表组件
import { CanvasRenderer } from "echarts/renderers";
// 按需引入渲染器(一般使用Canvas渲染器)

echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    VisualMapComponent,
    LineChart,
    MapChart,
    GaugeChart,
    CanvasRenderer,
]);
// 注册引入的组件

export default echarts;

main.js中引入并注册原型

import echarts from '@/utils/echarts';
Vue.prototype.$echarts = echarts

即可按往常使用ECharts库一样使用。


Ref

https://github.com/ecomfe/vue-echarts/blob/main/README.zh-Hans.md

Last modification:January 11, 2022
博客维护不易,如果你觉得我的文章有用,请随意赞赏