【vue】引入ECharts图表和组件

如何在Vue项目中画出优雅的图表?

ECharts
文档如下

https://www.echartsjs.com/tutorial.html#%E5%9C%A8%20webpack%20%E4%B8%AD%E4%BD%BF%E7%94%A8%20ECharts

引入步骤

  • 安装ECharts

    npm install echarts --save
    
  • 定义html容器用来渲染echarts图表

    <div class="chart" id="myChart" :style="{width: '500px', height: '500px'}"></div>
    
:style里可以设置图表大小
  • 引入echarts组件

    // 引入基本模板
    let echarts = require('echarts/lib/echarts')
    // 引入柱状图组件
    require('echarts/lib/chart/pie')
    require('echarts/lib/chart/bar')
    require('echarts-gl')
    
    // 组件
    require('echarts/lib/component/tooltip')
    require('echarts/lib/component/title')
    require("echarts/lib/component/dataset")
    
  • 初始化页面容器

    先设置一个页面变量mychart,在mounted函数或者created函数里

    this.myChart = echarts.init(document.getElementById('myChart'));
    
  • 配置图表option(关键)

    在画图的方法里(可以直接在mounted里或者点击事件之类的里面),定义一个option

    let option = {
        title:{ 
            text: me.title,
            left:'center',
            top:'5px',
            textStyle:{
                color:'#ccc',
                fontStyle:'normal',
                fontWeight:'bold',
                fontFamily:'sans-serif',
             fontSize:30
            }
        },
        tooltip:{},
        backgroundColor: '#2c343c',
        visualMap: {
            show: false,
            inRange: {
                colorLightness: [0.5, 1],
            }
        },
        series : [
            {
                name: '人数',
                type: me.type,
                radius: '55%',
                data: me.items,
                roseType: 'angle',
                label: {
                    normal: {
                        textStyle: {
                            color: 'rgba(255, 255, 255, 0.3)'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        lineStyle: {
                            color: 'rgba(255, 255, 255, 0.3)'
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        shadowBlur: 200,
                        shadowColor: 'rgba(0, 200, 150, 0.5)'
                    }
                }
            }
        ]
    };
    
  • title是指图表名,可以设置样式

  • tooltip类似于小提示,鼠标放在目标上会有提示框

  • visualMap可以设置图表的变化范围,可以事让结果更加明显

  • series里主要设置数据,不同类型的图表有不同的配置,上面代码是南丁格尔饼图的示例,一般设置type,有下面这些类型

    • bar 直方图
    • pie 饼图
    • bar3D 3D图(需要安装echarts-gl)
    • scatter 散点图
    • 等等…可以去官网查看更多类型
    • 引入dataset可以更方便管理数据,数据通过异步请求获取,传入前台的变量注入series里
  1. 注入页面容器

    me.myChart.setOption(option);
    

需要绘制3D图需要安装echats-gl,步骤和上面一致


结果如下

左下的那个条就是visualMap的效果


实际使用时并不需要引入echarts的所有组件,可以按需引入对应的模块列表

https://github.com/apache/incubator-echarts/blob/master/index.js

具体每种图表的配置都不太一样,讲起来太繁杂,需要时可以自行查阅

https://www.echartsjs.com/examples/