echarts 使用

目錄 內(nèi)容
2.1 formatter 各種標(biāo)簽自定義顯示方式
2.2 tooltip 自定義提示框的內(nèi)容
2.3 引入兩個(gè)不同組件的echarts圖表存在沖突 用ref
2.4一個(gè)chart多次渲染到div中 銷毀已經(jīng)存在的實(shí)例
2.5動(dòng)態(tài)的折線圖
2.6 ?;鶊D
2.7 液態(tài)球
2.8 儀表盤

(一)基礎(chǔ)

1.1 官網(wǎng):https://echarts.apache.org/handbook/zh/basics/import
1.2 安裝:npm install echarts --save
1.3 引入Echarts:
import * as echarts from 'echarts';

// 基于準(zhǔn)備好的dom,初始化echarts實(shí)例
var myChart = echarts.init(document.getElementById('main'));
// 繪制圖表
myChart.setOption({
  title: {
    text: 'ECharts 入門示例'
  },
  tooltip: {},
  xAxis: {
    data: ['襯衫', '羊毛衫', '雪紡衫', '褲子', '高跟鞋', '襪子']
  },
  yAxis: {},
  series: [
    {
      name: '銷量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }
  ]
});

(二) 具體問題

2.1 formatter

image.png

image.png

2.2 tooltip

自定義提示框的內(nèi)容

tooltop{
 formatter(params) {
            // console.log(params);
            let xiaoShou = params[0].data;
            let chengBen = params[1].data;
            let liRun = xiaoShou - chengBen;
            return `
            利潤 &nbsp;${liRun}萬元<br/>
            銷售額 &nbsp;${xiaoShou}萬元<br/>
            成本 &nbsp;${chengBen}萬元
            `;
          },
}

網(wǎng)頁上的寫法記錄


image.png

2.3 引入兩個(gè)不同組件的echarts圖表

存在沖突 因?yàn)殇秩镜絠d上 dom中只有一個(gè)id 會(huì)覆蓋

所以 這里使用ref來完成

這樣不會(huì)產(chǎn)生沖突了


image.png

2.4 一個(gè)chart多次渲染到div中 會(huì)報(bào)錯(cuò)

There is a chart instance already initialized on the dom

參考API:https://echarts.apache.org/zh/api.html#echarts.getInstanceByDom
這要求 我們再一次渲染chart時(shí) 需要銷毀原來的實(shí)例

  watch: {
    //監(jiān)聽switch的變化,來給echarts顏色變化
    switchValue: {
      handler(newValue) {
        // console.log("新的switchValue:", newValue);
        //-------------------dom中已經(jīng)有echarts實(shí)例對象 先銷毀-------------------
        //取得dom
        let chart = this.$refs.chart;
        // console.log(chart);
        //判斷是否已有案例
        let existInstance = echarts.getInstanceByDom(chart);
        // console.log(existInstance);
        if (existInstance) {
          if (true) {
            echarts.dispose(chart);
          }
        }
        //--------------------------清數(shù)據(jù)---------------------------------
        this.barZaizhi = [];
        this.ydseriesRuzhiata = [];
        this.seriesLizhi = [];
        this.xaxisData = [];
        //再一次初始化chart圖表
        this.getchart(newValue);
        //這個(gè)方法里面就是這樣的內(nèi)容
//           let myChart = echarts.init(this.$refs.chart);
//           myChart.setOption({})


      },
    },
  },

2.5動(dòng)態(tài)的折線圖

下面的實(shí)例 是監(jiān)聽父組件的按鈕響應(yīng) 來渲染chart

  • 步驟
    (1) 在data return 中 初始化 圖表
    (2) 得到指令 init :echarts
    (3) 在計(jì)時(shí)器中 間隔時(shí)間 獲取數(shù)據(jù)
    (4) 每次獲取的數(shù)據(jù) 都給到 data中初始化圖表中的對應(yīng)的data數(shù)據(jù)
    this.echartsOption.series[0].data = this.ydata;
<template>
  <!-- 動(dòng)態(tài)圖表 實(shí)現(xiàn) -->
  <div v-loading="loading" style="width: 100%; height: 100%">
    <div style="width: 100%; height: 100%" ref="chart"></div>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";

export default {
  name: "ScadaChart",

  data() {
    return {
      loading: false,
      xdata: [],
      ydata: [],
      // ----------------------------步驟1、折線圖 echarts 初始化----------------------------
      echartsOption: {
        grid: {
          top: "10%",
          left: "3%",
          right: "3%",
          bottom: "7%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.xdata,
          name: "時(shí)間",
          nameLocation: "end",
          axisLabel: {
            formatter: (value) => {
              // console.log(value, index);
              let value1 = value.substring(0, 10);
              let value2 = value.substring(11, 19);
              //   console.log(value1, value2);
              return `${value1}\n${value2}`;
            },
          },
        },
        yAxis: {
          type: "value",
          name: "車速",
          nameLocation: "end",
        },
        series: [
          {
            data: this.ydata,
            type: "line",
            symbol: "none",
          },
        ],
        tooltip: {
          show: true,
          trigger: "axis",
        },
      },
    };
  },
  props: {
    btn: Boolean,
    formheader: {
      type: Object,
    },
  },
  watch: {
    //監(jiān)聽 btn的變化 點(diǎn)擊按鈕 更新chart
    btn: {
      handler() {
        this.loading = true;
        //-------------------  dom中已經(jīng)有echarts實(shí)例對象 先銷毀   -------------------
        //取得dom
        let chart = this.$refs.chart;
        // console.log(chart);
        //判斷是否已有案例
        let existInstance = echarts.getInstanceByDom(chart);
        // console.log(existInstance);
        if (existInstance) {
          if (true) {
            echarts.dispose(chart);
          }
        }
        // this.getchart();
       // -----------------------------步驟2、監(jiān)聽到按鈕 開始echarts渲染------------------------ 
        this.myChart = echarts.init(this.$refs.chart);
        this.myChart.setOption(this.echartsOption);
        setInterval(() => {
          this.getdata();
        }, 10000);
      },
    },
  },

  methods: {
    //-----------------------------步驟3、獲取數(shù)據(jù)-----------------------------
    getdata() {
      let url = "http://36.26.85.213:8086/api/v2/query?org=th";
      let headers = {
        Authorization:
          "Token Z4s5lPSdXHs_zueTttAvcNQS9KyidZ-c4yOtiBaJltklkJWMk9EDla90idvh8kKkDp7eVIrRFoM5ByWB9AhFVA==",
        "Content-Type": "application/vnd.flux",
      };
      let data =
        'from(bucket: "tianheng")\n' +
        "|> range(start: -1h)\n" +
        // '|> filter(fn: (r) => r["_measurement"] == "sizing_10000012")\n' +
        '|> filter(fn: (r) => r["_measurement"] == ' +
        '"' +
        this.formheader.measurement +
        '"' +
        ")\n" +
        '|> filter(fn: (r) => r["machine_id"] == ' +
        '"' +
        this.formheader.machine_id +
        '"' +
        ")\n" +
        '|> filter(fn: (r) => r["_field"] == "current_speed")\n' +
        // "|> limit(n: 100)\n" +
        "|> timeShift(duration: 8h)\n";
      axios({
        url: url,
        method: "post",
        headers: headers,
        data: data,
      }).then((res) => {
        // console.log(res.data);
        // console.log(res.data.split(","));
        let data = res.data.split(",");
        //--------------------1、得到速度數(shù)據(jù)-------------------------------
        let value = data.indexOf("_value"); //找到value第一個(gè)位置 接下來每個(gè)數(shù)據(jù)+9
        let values = [];
        //1000 是 10 乘上 自己限制的數(shù)據(jù)長度
        //如果長度不限制 長度直接是data的長度
        for (let i = value + 9; i < data.length; i += 9) {
          // console.log(data[i]);
          // 返回的數(shù)據(jù)可能沒有100條 所以需要過濾
          if (data[i] != undefined) {
            values.push(data[i]);
          }
        }
        // console.log("_value", values);
        this.ydata = values;
        //--------------------2、得到時(shí)間數(shù)據(jù) --------------------------------
        let time = data.indexOf("_time"); //找到time第一個(gè)位置 接下來每個(gè)數(shù)據(jù)+9
        let times = [];
        for (let i = time + 9; i < data.length; i += 9) {
          // console.log(data[i]);
          // 返回的數(shù)據(jù)可能沒有100條 所以需要過濾
          if (data[i] != undefined) {
            times.push(data[i]);
          }
        }
        // console.log("_time", times);
        this.xdata = times;

        //  ---------------------步驟4、重新將數(shù)組賦值給echarts選項(xiàng)----------------
        this.echartsOption.xAxis.data = this.xdata;
        this.echartsOption.series[0].data = this.ydata;
        this.myChart.setOption(this.echartsOption);
        this.loading = false;
      });
    },
  },
};
</script>

<style  scoped>
</style>

2.6 桑基圖

注意: 因?yàn)槭莿?dòng)態(tài)的通過接口 得到數(shù)據(jù) ,所以需要 將data links 在data中賦值
注意 :data links 中的字段名字是要一樣的
option = {
    series: {
        type: 'sankey',
        layout: 'none',
        emphasis: {
            focus: 'adjacency'
        },
       //data:this.data
        data: [{
            name: 'a'
        }, {
            name: 'b'
        }, {
            name: 'a1'
        }, {
            name: 'a2'
        }, {
            name: 'b1'
        }, {
            name: 'c'
        }],
      // links:this.links
        links: [{
            source: 'a',
            target: 'a1',
            value: 5
        }, {
            source: 'a',
            target: 'a2',
            value: 3
        }, {
            source: 'b',
            target: 'b1',
            value: 8
        }, {
            source: 'a',
            target: 'b1',
            value: 3
        }, {
            source: 'b1',
            target: 'a1',
            value: 1
        }, {
            source: 'b1',
            target: 'c',
            value: 2
        }]
    }
};

2.7 液態(tài)球

image.png
  • 報(bào)錯(cuò) 是因?yàn)?code>echatrs和echarts-liquidfill版本的原因
  • 解決 echart@4.9.0 echarts-liquidfill@2.0.6
  • 解決 echart@4.2.1 echarts-liquidfill@2.0.6
import echarts from "echarts";
import "echarts-liquidfill";
// npm install echarts-liquidfill

一個(gè)頁面有多個(gè)chart 的配置方法

   <div
     class="content-item-content-right-chart"
    :id="waveId(index)"
   ></div>


    waveId(i) {
      let waveid = "waveChart" + i;
      return waveid;
    },


    initWave(i, v) {
      let color = [v >= this.peiZhi.xiaolvMin ? "#23b899" : "#ff0000"];
      let bgcolor = [
        v >= this.peiZhi.xiaolvMin
          ? "rgba(35, 184, 153,0.2)"
          : "rgb(255, 0, 0,0.2)",
      ];
      this.chart[i] = echarts.init(document.getElementById("waveChart" + i));
      this.chart[i].setOption({
        series: [
          {
            type: "liquidFill",
            //圖大小
            radius: "80%",
            waveAnimation: true,
            data: [v / 100],
            color: color,
            //圓圈內(nèi)的背景顏色
            backgroundStyle: {
              color: bgcolor,
            },
            //圈內(nèi)的文字 不要
            label: {
              show: false,
            },
            outline: {
              show: true,
              borderDistance: 2,
              itemStyle: {
                borderWidth: 2,
                borderColor: color,
                shadowBlur: 8,
                shadowColor: color,
              },
            },
          },
        ],
      });
    },

2.8 儀表盤 進(jìn)度條

  • 問題 :

echarts的版本 會(huì)影響儀表盤的樣式,進(jìn)度條這個(gè)樣式就會(huì)出不來

  • 解決:

1.echarts 高版本 直接可以用官方的代碼。
2.echarts 低版本 主要是 axisLine lineStyle color中的設(shè)置

//低版本
      this.chart[i].setOption({
        backgroundColor: "#fff",
        series: [
          {
            type: "gauge",
            center: ["50%", "80%"],
            clockwise: true, //刻度是否順時(shí)針增長
            startAngle: 180, //指針開始0的位置
            endAngle: 0, //指針結(jié)束位置
            min: 0,
            max: speedMax,
            clockwise: true, // 儀表盤刻度是否是順時(shí)針增長,默認(rèn) true。
            splitNumber: 10,
            radius: "125%", //大小
            pointer: {
              //指針
              show: true,
              width: 2,
              showAbove: true,
              length: "70%",
            },
            itemStyle: {
              //儀表盤指針樣式
              color: color,
              shadowColor: color,
              shadowBlur: 4,
              shadowOffsetX: 2,
              shadowOffsetY: 2,
            },
            axisLine: {
              //儀表盤軸線樣式
              show: true,
              roundCap: true,
              lineStyle: {
                width: 8,
                color: [
                  [v / speedMax, color],
                  [1, "#e6ebf8"],
                ],
              },
            },
            progress: {
              show: true,
              width: 6,
              //   overlap: false, //多組數(shù)據(jù) 是否重疊
              //   roundCap: true, //是否在兩端顯示成圓形
              itemStyle: {
                color: color,
              },
            },
            axisTick: {
              //刻度樣式
              show: false, //
              //   distance: 130,
              splitNumber: 1, //分隔線之間分割的刻度數(shù)
              length: 3,
              lineStyle: {
                width: 3,
                color: color,
                type: "solid",
                cap: "round",
              },
            },
            splitLine: {
              //分隔線樣式
              show: false, //
              distance: 0, //離軸線的距離
              length: 2,
              lineStyle: {
                width: 2,
                color: color,
                type: "solid",
              },
            },
            axisLabel: {
              show: false,
            },
            title: {
              show: false,
            },
            detail: {
              show: false,
            },
            data: [
              {
                value: v,
                name: "車速",
              },
            ],
          },
        ],
      });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容