Vue-ECharts使用说明
vue-echarts 是在Apache Echarts官网的echarts使用方法上二次封装的组件,方便我们创建echarts图应用到我们的项目中。
参考:
vue-echarts 官网:https://github.com/ecomfe/vue-echarts
Apache Echarts 官网:https://echarts.apache.org/zh/index.html
1-安装
1、安装echarts、vue-echarts模块
npm insatll echarts vue-echarts
2、如果是vue2(vue version < 2.8.0)的环境,需要安装@vue/composition-api模块
npm i -D @vue/composition-api
2-示例
下面以一个折线图为例子进行说明
<template> <div style="height: 100%;"> <v-chart class="chart" :option="option" autoresize /> </div> </template> <script> // 官方:按需引入echarts所需的模块 import { use } from 'echarts/core'; import { LineChart } from 'echarts/charts'; import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'; import { CanvasRenderer } from 'echarts/renderers'; // 第三方组件模块 import VChart from 'vue-echarts'; // 注册安装模块(插件) use([ CanvasRenderer, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent ]) export default { name: 'LineCharts', components: { //注册组件 VChart }, data: function() { return { option: { //配置选项属性 xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] }, yAxis: { type: 'value' }, series: [ { data: [150, 230, 224, 218, 135, 147, 260], type: 'line' } ] } } } }
复制
之后,在任意模版页面使用这个折线图的组件即可,也可以按照上面的格式直接在模版页面中使用(代码冗余),使用效果如下:
在上面的示例中,我们引入的第三方模块组件,也就是Vue-echarts这个模块下封装的组件,直接使用该组件我们就不需要按照官网的注册方式去初始化chart的dom元素,也不需要通过setOption去注册option选项配置,简化了操作。
除去引入该组件这部操作,其他部分都是按照echarts官方示例代码中按需引入的方式编写;也就是引入echarts/core中的use注册方法、图例、图例中用到的选项组件模块以及echarts/renderers中的渲染函数。
注意:
有的模块可能没有看到具体在哪里使用,但是如果页面渲染不正常,就可以在游览器控制台看具体是哪一个模块没有引发了报错,根据报错提示信息引入即可。
常见的这类模块比如 GridComponent、TooltipComponent、CanvasRenderer 等。
3-自定义优化图表思路
在上面介绍完了vue-echarts的便捷使用,如果我们需要直接自定义图,一般的步骤是:
- 在Apache Echarts官网的示例中[https://echarts.apache.org/examples/zh/index.html]找到你想要做图的类型(比如折线图、饼图、散点图等),引入大致的代码模块结合vue-echarts进行渲染。
- 基本能够渲染示例之后,你就需要去编写option配置了,该配置复杂的不在数据,其实很多时间是在调整样式,具体每个属性对应的样式调节可以参考Apache Echarts官网的配置API[https://echarts.apache.org/zh/option.html#title]进行查阅。