目录

第1关:Vue+Echarts 的简单使用

任务描述

相关知识

安装 echarts 依赖

创建 echarts 图表

按需引入

以组件的形式用 echarts

编程要求

测试说明

代码文件

图形化操作

第2关:Vue+Echarts 的多图表组合使用

任务描述

相关知识

Echarts 图表代码的编写

vue 结合 echarts 绘制单个图表

vue 结合 echarts 绘制多个图表

编程要求

测试说明

代码文件

图形化操作


第1关:Vue+Echarts 的简单使用

任务描述

本关任务:编写一个完成在 vue 中集成 echarts 的程序。

相关知识

为了完成本关任务,你需要掌握:

  1. 安装 echarts 依赖;

  2. 创建 echarts 图表;

  3. 按需引入;

  4. 以组件的形式用 echarts。

在上一章节中我们已经了解过 Echarts 的简单使用了,之前也有了解过 Vue 的一些使用方法以及注意事项,所以我们就直接进入正题,来讲解 Vue 跟 Echarts 的接法。

安装 echarts 依赖
  1. npm install echarts -S

或者使用淘宝的镜像(推荐,速度占优)

  1. npm install -g cnpm --registry=https://registry.npm.taobao.org
  2. cnpm install echarts -S
创建 echarts 图表

首先需要全局引入,在 main.js 中:

 
  1. // 引入echarts
  2. import echarts from 'echarts'
  3. Vue.prototype.$echarts = echarts

其次在 Echarts.vue (也就是我们默认程序中的 App.vue)中准备实例 echarts 图表,这里我们选择官网中的一个简单实例——柱状图: <div id="myChart" :style="{width: '300px', height: '300px'}"></div>

 
  1. export default {
  2. name: 'hello',
  3. data () {
  4. return {
  5. msg: 'Welcome to Your Vue.js App'
  6. }
  7. },
  8. mounted(){
  9. this.drawLine();
  10. },
  11. methods: {
  12. drawLine(){
  13. // 基于准备好的dom,初始化echarts实例
  14. let myChart = this.$echarts.init(document.getElementById('myChart'))
  15. // 绘制图表
  16. myChart.setOption({
  17. title: { text: '在Vue中使用echarts' },
  18. tooltip: {},
  19. xAxis: {
  20. data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
  21. },
  22. yAxis: {},
  23. series: [{
  24. name: '销量',
  25. type: 'bar',
  26. data: [5, 20, 36, 10, 10, 20]
  27. }]
  28. });
  29. }
  30. }
  31. }

注意:我们要在 mounted 生命周期函数中实例化 echarts 对象。因为我们要确保 dom 元素已经挂载到页面中。

这样一个简单的图表就完成了,还是比较简单的。假如在一个大型的项目中,而且数据是非常复杂的?那么该如何操作?

按需引入

由于全局引入会将所有的 echarts 图表打包,导致体积过大。 在 Echarts.vue 文件中:

 
  1. // 引入基本模板
  2. let echarts = require('echarts/lib/echarts')
  3. // 引入柱状图组件
  4. require('echarts/lib/chart/bar')
  5. // 引入提示框和title组件
  6. require('echarts/lib/component/tooltip')
  7. require('echarts/lib/component/title')

使用 require 而不是 import,因为基于前面的疑问,加上实际运用到项目中遇到的一些问题,我建议大家使用组件的形式。

以组件的形式用 echarts

从上边可以看出,你每次在使用 echarts 的时候,都必须要重复的引入,这样很不方便,vue 作为一个组件化开发的框架,我们可以使用组件的方式进行集成。每次我们引入组件,进行使用,这样就方便的多。 下面我们就对 echarts 进行的一个简单的 vue 组件的集成。 在 echarts 中,子组件:

props 部分是我接收到的参数,父组件获取数据分发,data 是父组件分发给 echarts 的数据源。

父组件:

如果在大型的项目,而且图表又非常的多,那么 vuex 少不了。如果把数据集中存储到了 vuex 中,echarts 组件再从 vuex 中获取数据,我们也能随时保存获取的结果,对这些数据可以添加收藏也可以加入缓存中,下次再请求可以先从缓存调用。

编程要求

根据提示,在右侧编辑器_______处补充代码,完成在 vue 中集成 echarts 的程序。 具体步骤:

  1. 补充代码文件;

  2. 在图形化界面打开终端,并进入 Desktop/workspace/myshixun/step1 目录下;

  3. 采用 npm install 命令安装依赖;

  4. 采用命令 npm run serve 命令运行项目;

  1. 打开平台浏览器输入 localhost:8080 即可查看效果。

测试说明

平台会对你编写的代码进行测试,这里提供给大家一张运行截图:

注意:因随机数据和时间不做图像对比,本关评测内容为测试 Vue 服务是否成功启动。通关之后平台会将端口 kill 掉,需要重新启动,启动命令为 npm run serve。

预计输出:

 
  1. Vue 服 务 启 动 成 功
  2. 恭喜你完成在 vue 中集成 echarts 的程序

开始你的任务吧,祝你成功!

代码文件

<template>
  <div class="my-container">
    <div class="nowEcharts" id="nowEcharts"></div>
  </div>
</template>
<script>
/********** begin **********/
import echarts from "echarts";
export default {
  data() {
    return {
      oneDay: 1000,
      nowOptions: {
        visualMap: [
          {
            show: false,
            type: "continuous",
            seriesIndex: 0,
            min: 0,
            max: 400,
          },
        ],
        title: {
          left: "left",
          text: "电量消耗实时统计",
        },
        tooltip: {
          trigger: "axis",
          formatter: function (params) {
            params = params[0];
            var date = new Date(params.name);
            return (
              date.getDate() +
              "/" +
              (date.getMonth() + 1) +
              "/" +
              date.getFullYear() +
              " : " +
              params.value[1]
            );
          },
          axisPointer: {
            animation: false,
          },
        },
        grid: {
          top: "15%",
          bottom: "10%",
        },
        xAxis: {
          type: "time",
          splitLine: {
            show: false,
          },
          //设置 triggerEvent 属性为 true
          triggerEvent: true,
        },
        yAxis: {
          type: "value",
          boundaryGap: [0, "100%"],
          max: 100,
          //设置 splitLine 属性为 false
          splitLine: {
            show: false,
          },
        },
        series: [
          {
            //设置图形为折线图 line
            type: "line",
            showSymbol: false,
            hoverAnimation: false,
            data: [],
          },
        ],
      },
      myChart: null,
      timer: null,
      data: [],
      temp: 59,
      now: "",
    };
  },
/********** end **********/
  mounted() {
    this.nowChart();
    this.getData()
  },
  methods: {
    //   初始化图表
    nowChart() {
      let that = this;
      this.now = +new Date();
      var value = Math.random() * 1000;
      for (var i = 0; i < 60; i++) {
        this.now = new Date(+this.now + this.oneDay);
        this.data.push(this.randomData(this.now, value));
      }
      // 基于准备好的dom,初始化echarts实例
      this.myChart = echarts.init(document.getElementById("nowEcharts"));

      // 绘制图表
      let options = Object.assign(that.nowOptions, {});
      options.series.forEach((item) => {
        item.data = that.data;
        item.markPoint = {
          data: [
            [
              {
                symbol: "none",
                x: "95%",
              },
              {
                symbol: "circle",
                name: "实时数据",
                value: this.data[this.temp].value[1],
                xAxis: this.data[this.temp].value[0],
              },
            ],
          ],
        };
      });
      this.myChart.setOption(options);

    },
    // 获取接口返回数据 这里用定时器模拟一秒一个数据
    getData() {
      let that = this;
      var value = Math.random() * 1000;
      this.timer = setInterval(() => {
        for (var i = 0; i < 1; i++) {
          that.data.shift();
          that.now = new Date(+that.now + that.oneDay);
          that.data.push(this.randomData(that.now, value));
        }
        that.updateChart()
      }, 1000);
    },
    //更新图表
    updateChart() {
      let options = Object.assign(this.nowOptions, {});
      options.series.forEach((item) => {
        item.data = this.data;
        item.markPoint = {
          data: [
            [
              {
                symbol: "none",
                x: "95%",
              },
              {
                symbol: "circle",
                name: "实时数据",
                value: this.data[this.temp].value[1],
                xAxis: this.data[this.temp].value[0],
              },
            ],
          ],
        };
      });
      this.myChart.setOption(options);
    },
    // 产生随机数
    randomData(now, value) {
      value = Math.random() * 100;
      var valueName =
        now.getFullYear() +
        "/" +
        (now.getMonth() + 1) +
        "/" +
        now.getDate() +
        " " +
        (now.getHours() >= 10 ? now.getHours() : "0" + now.getHours()) +
        ":" +
        (now.getMinutes() >= 10 ? now.getMinutes() : "0" + now.getMinutes()) +
        ":" +
        (now.getSeconds() >= 10 ? now.getSeconds() : "0" + now.getSeconds());
      return {
        name: now.toString(),
        value: [valueName, Math.round(value)],
      };
    },
  },
};
</script>
<style >
.nowEcharts {
  width: 100%;
  height: 300px;
}
</style>

图形化操作

        按照上面的提示,一步步在虚拟机里面操作即可。

第2关:Vue+Echarts 的多图表组合使用

任务描述

本关任务:编写一个完成 vue 结合 echarts 绘制多个图表的程序。

相关知识

为了完成本关任务,你需要掌握:

  1. Echarts 图表代码的编写;
  2. vue 结合 echarts 绘制单个图表;
  3. vue 结合 echarts 绘制多个图表。
Echarts 图表代码的编写

echarts 官方 demo 地址:

首先进入 echarts 网址中,我们能看到,图表的主要参数都在 option 这函数里,如图1所示。我们将 option() 放到 vue 中的 methods 中即可引用(这里以饼图为例)。

vue 结合 echarts 绘制单个图表

打开项目,创建 views 文件夹,存放父组件 index.vue,在 components 文件夹下创建 echartscom.vue 子组件,如下图所示。 echartscom.vue 中主要放 option(),用来实现图表渲染,index.vue 存放数据,echartscom.vue 引用 index.vue 的数据从而形成父子组件间的传值

思路说完了,接下来就是代码,结合代码可能大家会更好的理解

子组件,echartscom.vue

 
  1. <!-- echartscom.vue -->
  2. <template>
  3. <div class="charttest">
  4. <div style="width:400px;height:400px;" :id="echarts" class="echarts" ref="echarts">
  5. </div>
  6. </div>
  7. </template>
  8. <script>
  9. import echarts from 'echarts'
  10. export default {
  11. name:'echartscom',
  12. data() {
  13. return {};
  14. },
  15. methods: {
  16. drawCharts() {
  17. var myChart = echarts.init(document.getElementById(this.echarts));
  18. myChart.setOption({
  19. tooltip: {
  20. trigger: 'item',
  21. formatter: '{a} <br/>{b}: {c} ({d}%)'
  22. },
  23. legend: {
  24. orient: 'vertical',
  25. x: 'left',
  26. data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  27. },
  28. series: [
  29. {
  30. name: '访问来源',
  31. type: 'pie',
  32. radius: ['50%', '70%'],
  33. avoidLabelOverlap: false,
  34. label: {
  35. normal: {
  36. show: false,
  37. position: 'center'
  38. },
  39. emphasis: {
  40. show: true,
  41. textStyle: {
  42. fontSize: '30',
  43. fontWeight: 'bold'
  44. }
  45. }
  46. },
  47. labelLine: {
  48. normal: {
  49. show: false
  50. }
  51. },
  52. data: [
  53. { value: 335, name: '直接访问' },
  54. { value: 310, name: '邮件营销' },
  55. { value: 234, name: '联盟广告' },
  56. { value: 135, name: '视频广告' },
  57. { value: 1548, name: '搜索引擎' }
  58. ]
  59. }
  60. ]
  61. });
  62. }
  63. },
  64. computed: {
  65. echarts() {
  66. return 'echarts' + Math.random() * 100000;
  67. }
  68. },
  69. mounted() {
  70. this.drawCharts();
  71. },
  72. components: {}
  73. };
  74. </script>
  75. <style>.a8e7d587f-f6e2-4a80-a368-41624fc097e0 </style>```父组件,`index.vue````python<!-- index.vue --><template> <echartscom /></template><script> import echartscom from '@/components/echartscom.vue' export default { data() { return {}.a8e7d587f-f6e2-4a80-a368-41624fc097e0 ; }.a8e7d587f-f6e2-4a80-a368-41624fc097e0 , methods: { }.a8e7d587f-f6e2-4a80-a368-41624fc097e0 , mounted() {}.a8e7d587f-f6e2-4a80-a368-41624fc097e0 , components: { echartscom }.a8e7d587f-f6e2-4a80-a368-41624fc097e0 }.a8e7d587f-f6e2-4a80-a368-41624fc097e0 ;</script><style></style>

有关于组件的集成上一关卡我们已经讲解,大家有需要也可以深入的去了解一下。 运行效果图如下:

目前为止,我们的工作完成大半了,接下来就是父子间传值了。传值目前我们用 props,vuex 以后会说到,并且小型项目的话,用 vuex 显得繁琐庞大,因此不建议用,等到项目较大,多个父子页面传值时,vuex 便如神兵天降。

说一下 props 传值思路,在父组件中,把值放在 data()中,子组件通过 props 引入父组件的数组名,即可传值,对 props 感兴趣的朋友可以专门上百度 、google、bing 学习。

vue 结合 echarts 绘制多个图表
 
  1. props: {
  2. 父组件数组名: {
  3. type: Array,
  4. default: () => []
  5. }
  6. },

父组件:index.vue

 
  1. <!-- index.vue -->
  2. <template>
  3. <div>
  4. <div v-for="(chardata,index) in msg" :key="index" class="test">
  5. <echartscom :chartData="chardata" autoresize />
  6. </div>
  7. </div>
  8. </template>
  9. <script>
  10. import echartscom from '@/components/echartscom.vue'
  11. export default {
  12. data() {
  13. return {
  14. msg:{
  15. chartData1: [
  16. {value:335, name:'直接访问'},
  17. {value:310, name:'邮件营销'},
  18. {value:234, name:'联盟广告'},
  19. {value:135, name:'视频广告'},
  20. {value:1548, name:'搜索引擎'}
  21. ],
  22. chartData2: [
  23. {value:335, name:'直接访问'},
  24. {value:310, name:'邮件营销'},
  25. {value:234, name:'联盟广告'},
  26. {value:135, name:'视频广告'},
  27. {value:1548, name:'搜索引擎'}
  28. ],
  29. }
  30. };
  31. },
  32. methods: {
  33. },
  34. mounted() {},
  35. components: {
  36. echartscom
  37. }
  38. };
  39. </script>
  40. <style>.a8e7d587f-f6e2-4a80-a368-41624fc097e0 .test{ float: left; </style>

子组件:echartscom.vue

 
  1. <!-- echartscom.vue -->
  2. <template>
  3. <div class="charttest">
  4. <div style="width:400px;height:400px;" :id="echarts" class="echarts" ref="echarts">
  5. </div>
  6. </div>
  7. </template>
  8. <script>
  9. import echarts from 'echarts'
  10. export default {
  11. name:'echartscom',
  12. props: {
  13. chartData: {
  14. type: Array,
  15. default: () => []
  16. }
  17. },
  18. data() {
  19. return {
  20. };
  21. },
  22. methods: {
  23. drawCharts() {
  24. var myChart = echarts.init(document.getElementById(this.echarts));
  25. myChart.setOption({
  26. tooltip: {
  27. trigger: 'item',
  28. formatter: '{a} <br/>{b}: {c} ({d}%)'
  29. },
  30. legend: {
  31. orient: 'vertical',
  32. x: 'left',
  33. data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
  34. },
  35. series: [
  36. {
  37. name: '访问来源',
  38. type: 'pie',
  39. radius: ['50%', '70%'],
  40. avoidLabelOverlap: false,
  41. label: {
  42. normal: {
  43. show: false,
  44. position: 'center'
  45. },
  46. emphasis: {
  47. show: true,
  48. textStyle: {
  49. fontSize: '30',
  50. fontWeight: 'bold'
  51. }
  52. }
  53. },
  54. labelLine: {
  55. normal: {
  56. show: false
  57. }
  58. },
  59. data: this.chartData
  60. }
  61. ]
  62. });
  63. }
  64. },
  65. computed: {
  66. echarts() {
  67. return 'echarts' + Math.random() * 100000;
  68. }
  69. },
  70. mounted() {
  71. this.drawCharts();
  72. },
  73. components: {}
  74. };
  75. </script>
  76. <style></style>

此时浏览器自动刷新,看一下结果如下图所示:

编程要求

根据提示,在右侧编辑器补充代码,完成 vue 结合 echarts 绘制多个图表 。 具体步骤:

  1. 补充代码文件;

  1. 在图形化界面打开终端,并进入 Desktop/workspace/myshixun/step2 目录下;

  2. 采用 npm install 命令安装依赖;

  3. 采用命令 npm run serve 命令运行项目;

  1. 打开平台浏览器输入 localhost:8081 即可查看效果。

测试说明

平台会对你编写的代码进行测试,这里提供给大家一张运行截图:


注意:因随机数据不做图像对比,本关评测内容为测试 Vue 服务是否成功启动,如若图表显示不全可以尝试缩小浏览器当前页面再刷新查看(Ctrl+鼠标滚轮)

预计输出:

 
  1. Vue 服 务 启 动 成 功
  2. 恭喜你完成在 Vue+Echarts 的多图表组合使用

开始你的任务吧,祝你成功!

代码文件

<template>
  <div id="app">
    <!-- 折线 -->
    <LineChart />
    <!-- 柱状图 -->
    <LineChart2 />
     <!-- 有错误 -->
    <RaceChart />
    <!-- 柱状图 -->
    <RaceChart_1 />
    <!-- 待研究 -->
    <RaceChart_2 />
  </div>
</template>

<script>
/********** begin **********/
//分别导入 ./components/ 目录下的 LineChart、LineChart2、RaceChart、RaceChart_1和RaceChart_2 vue配置文件


import LineChart from './components/LineChart.vue'
import LineChart2 from './components/LineChart2.vue'
import RaceChart from './components/RaceChart.vue'
import RaceChart_1 from './components/RaceChart_1.vue'
import RaceChart_2 from './components/RaceChart_2.vue'

/********** end **********/
export default {
  name: 'app',
  components: {
    LineChart,
    LineChart2,
    RaceChart,
    RaceChart_1,
    RaceChart_2
  }
}
</script>

<style>

</style>

图形化操作

        按照上面的提示,一步步在虚拟机里面操作即可。

更多推荐