1 - vue项目中使用echarts

318 阅读1分钟

案例的仓库地址:gitee.com/mayxue/vue2…

效果:

实现的功能:

  1. 修改鼠标经过拐点tooltip展示数据的规则,例如:给数字的最后两位前面加逗号
  2. 给折线图的拐点替换成图片
  3. 让图表自适应浏览器大小

一、安装

1. 安装echarts依赖

npm install echarts -S

2. 使用国内的淘宝镜像安装依赖

//1.先安装淘宝镜像
npm install -g cnpm --registry=<https://registry.npm.taobao.org>
//2.安装echarts依赖
cnpm install echarts -S

二、全局引入

1. 在main.js中引入

import * as echarts from 'echarts' // 高版本的echarts需要这样引用才不会报错
Vue.prototype.$echarts = echarts

三、在页面中使用echarts

1. template代码

<template>
  <div class="echart">
    <el-card :body-style="{ padding: '20px', minHeight: 'calc(100vh - 100px)' }">
      <div id="statistics_eharts" ref="chart"></div>
    </el-card>
  </div>
</template>

2. echart必须要设置宽高才可以正常渲染

<style lang="scss" scoped>
#statistics_eharts {
  width: calc(100vw - 260px);
  height: 600px;
}
</style>

3. script代码:

<script>
export default {
  name: "echart",
  components: {},
  data() {
    return {
      option: {
        title: {
          text: "用户数量/领取数量",
          textStyle: {
            color: "#000",
            fontSize: 16
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器,坐标轴触发有效
            type: "shadow" // 默认为直线,可选为:'line' | 'shadow'
          },
          textStyle: {
            align: "left" //文本左对齐
          },
          //改变鼠标移上去,修改图表数据的显示格式(数据的百位的时候加‘,’)
          formatter: function(params, ticket, callback) {
            console.log("params", params);
            var res = "" + params[0].name;
            for (var i = 0; i < params.length; i++) {
              console.log("i", i);
              let oSpan =
                '<span style="background:' +
                params[i].color +
                ';width:10px;height:10px;border-radius: 50%;display: inline-block;marign-right:5px;marign-bottom:5px"></span>';
              res +=
                "<br/>" +
                oSpan +
                " " +
                params[i].seriesName +
                " : " +
                params[i].value.toString().replace(/(?=(\B)(\d{2})$)/, ",$1");
            }
            return res;
          }
        },
        legend: {
          left: "580",
          data: ["用户数量", "领取数量"] //统计的数据
        },
        grid: {
          bottom: "3%",
          left: "5%",
          right: "7%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            //x轴字体颜色
            axisLine: {
              lineStyle: {
                color: "#000"
              }
            },
            splitLine: {
              show: false //隐藏网格
            },
            data: [], //x轴的数据
            axisPointer: {
              type: "shadow",
              shadowStyle: {
                // 阴影指示器样式设置
                color: "rgba(1,127,90,0.1)" // 阴影颜色
              },
              splitLine: {
                show: false //隐藏网格
              },
              splitArea: {
                show: false //隐藏网格
              }
            },
            axisLabel: {
              show: true
            }
          }
        ],
        //如果要用到2个y轴,就需要配置两个y轴
        yAxis: [
          {
            type: "value",
            x: "center",
            name: "(用户数量)",
            min: 0,
            // max: 100,
            show: true,
            //y轴颜色
            axisLine: {
              show: true,
              lineStyle: {
                color: "#000"
              }
            },
            splitLine: {
              show: true //隐藏网格
            },
            splitArea: {
              show: false //隐藏网格背景
            }
          },
          {
            type: "value",
            name: "(领取数量)",
            x: "center",
            min: 0,
            // max: 100,
            //y轴颜色
            axisLine: {
              show: true, //是否显示y轴的竖线
              lineStyle: {
                color: "#000"
              }
            },
            splitLine: {
              show: false //隐藏网格
            },
            splitArea: {
              show: false //隐藏网格背景
            }
          }
        ],
        series: [] //图表的数据
      }
    };
  },
  methods: {
    chartsInfo() {
      this.option.series = [];
      let timeData = [],
        userData = [],
        receiveData = [],
        //模拟后台返回的数据
        res = {
          xAxis: [
            "04/24",
            "04/25",
            "04/26",
            "04/27",
            "04/28",
            "04/29",
            "04/30",
            "05/01",
            "05/02",
            "05/03"
          ],
          userData: [
            {
              name: "用户数量",
              data: [27987, 4352, 4278, 3802, 377, 70, 260, 300, 158, 89]
            }
          ],
          //symbol--给拐点设置图片
          receiveData: [
            {
              name: "领取数量",
              data: [
                700,
                2670,
                3070,
                1458,
                859,
                285,
                187,
                205,
                130,
                {
                  value: 221,
                  symbol:
                    "image://https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
                  symbolSize: 30
                }
              ]
            }
          ]
        };

      timeData = res.xAxis; //x轴的数据:日期
      userData = res.userData[0].data; //
      receiveData = res.receiveData[0].data; //
      this.option.xAxis[0].data = res.xAxis; //x轴的数据:日期

      let echartData = [
        {
          name: "用户数量",
          data: userData,
          color: "#02a9f1",
          echartType: "bar",
          yIndex: 1
        },
        {
          name: "领取数量",
          data: receiveData,
          color: "#ff8400",
          echartType: "line",
          yIndex: 0
        }
      ];
      for (let i = 0; i < echartData.length; i++) {
        this.option.series.push({
          name: echartData[i].name,
          type: echartData[i].echartType,
          itemStyle: {
            normal: {
              lineStyle: {
                width: 3 //折线图的粗细
              }
            }
          },
          // barWidth: 6,
          smooth: true, //让曲线平滑
          yAxisIndex: echartData[i].yIndex, //用的第几个y轴
          color: echartData[i].color,
          data: echartData[i].data
        });
      }

      let chartDom = this.$refs.chart;
      let myChart = this.$echarts.init(chartDom); //初始化echarts实例
      myChart.setOption(this.option, true); //设置为true的话,就是notMerge,不合并;false的话,就Merge,之前的东西还保留~
      window.onresize = myChart.resize; //图表自适应浏览器大小

      //给echart添加点击事件
      myChart.on("click", function(params) {
        console.log(params.name); //获取x轴的值
      });
    }
  },
  mounted() {
    this.chartsInfo();
  }
};
</script>

四、功能点拆分

1. 修改鼠标移到图表上,显示格式的修改

1.1 统一改变数据的显示格式:valueFormatter

官方api:echarts.apache.org/zh/option.h…

option = {
  tooltip: {
    trigger: 'axis',
    valueFormatter: (value) => value.toString().replace(/(\d{2})$/, ",$1")
  },
};

2.改变部分数据的显示格式:tooltip-->formatter

option = {
  tooltip: {
      trigger: "axis",
      axisPointer: {
        // 坐标轴指示器,坐标轴触发有效
        type: "shadow" // 默认为直线,可选为:'line' | 'shadow'
      },
      //改变鼠标移上去,图表数据的显示格式(邮米领取总额,邮米下单总额,邮米核销总额)百位的时候加‘,’
      formatter: function(params, ticket, callback) {
        var res = "" + params[0].name;
        for (var i = 0; i < params.length; i++) {
          let oSpan =
            '<span style="background:' +
            params[i].color +
            ';width:10px;height:10px;border-radius: 50%;display: inline-block;marign-right:5px;marign-bottom:5px"></span>';
          if (i > 1) {
            res +=
              "<br/>" +
              oSpan +
              " " +
              params[i].seriesName +
              " : " +
              params[i].value.toString().replace(/(\d{2})$/, ",$1") +
              "";
          } else {
            res +=
              "<br/>" +
              oSpan +
              " " +
              params[i].seriesName +
              " : " +
              params[i].value;
          }
        }
        return res;
      }
    },
};

2. 图表有不同维度的数据,用2个不同的y轴显示

option: {
  //如果要用到2个y轴,就需要配置两个y轴
  yAxis: [
    {
      type: "value",
      x: "center",
      name: "(用户数量)",
      min: 0,
      // max: 100,
      show: true,
      //y轴颜色
      axisLine: {
        show: true,
        lineStyle: {
          color: "#000"
        }
      },
      splitLine: {
        show: true //隐藏网格
      },
      splitArea: {
        show: false //隐藏网格背景
      }
    },
    {
      type: "value",
      name: "(领取数量)",
      x: "center",
      min: 0,
      // max: 100,
      //y轴颜色
      axisLine: {
        show: true, //是否显示y轴的竖线
        lineStyle: {
          color: "#000"
        }
      },
      splitLine: {
        show: false //隐藏网格
      },
      splitArea: {
        show: false //隐藏网格背景
      }
    }
  ],
}

3. 给折线图的拐点设置图片--利用symbol

// data的格式:
data: [
  700,
  2670,
  3070,
  1458,
  859,
  285,
  187,
  205,
  130,
  {
    value: 221,
    symbol:
    "image://https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
    symbolSize: 30
  }
]

4. 让图表自适应浏览器大小

window.onresize = myChart.resize; //图表自适应浏览器大小

5. 给echart添加点击事件

myChart.on("click", function(params) {
  console.log(params.name); //获取x轴的值
});