【echarts在vue的简单使用及随窗口移动而自适应变化大小】

关于echarts图表随窗口移动变化,直接看代码
1、旧版本

<template>
  <div ref="chart" class="chart" style="width:100%;height: 400px;"/>
</template>

<script>
/* eslint-disable */
//获取数据接口
  import { getDataApiStatistic } from "@/api/metadata/home.js";
  //局部引入echarts
  import echarts from "echarts";
  export default {
    name: "NumberOfLogins",
    data() {
      return {
        resizeTimer: null,
        chart: null,
        keys: [0, 0, 0],
      };
    },
    mounted() {
    //自适应
      window.addEventListener("resize", this.resize);  //只要窗口大小发生像素变化就会触发
      
           > * 页面加载完毕加载  window.addEventListener("load",function(){})
           > * 页面加载成功元素就可以  window.addEventListener("DOMContentLoaded",function(){})
           > * echarts.init是vue原型中$echarts提供的方法,接收三个参数:dom,theme,opts
           > * this.$refs.chart是参数1容器
           
      this.chart = echarts.init(this.$refs.chart);
      this.draw();
      this.getdata();
    },
    beforeDestroy() {
      window.removeEventListener("resize", this.resize);
      this.chart.dispose();  //销毁
    },
    methods: {
      draw() {
        this.chart.setOption({
          title: {
            text: "数据服务数量统计",
            right: "center",
            top: "5%",
            textStyle: {
              color: "#516B91",
            },
          },
          tooltip: {
            trigger: "item",
          },
          legend: {
            top: "5%",
            left: "20px",
            orient: "vertical",  //设置图例的朝向 垂直显示
            align: "left",
            itemGap: 10,
            itemHeight: 20,
            itemWidth: 20,
            textStyle: {
              color: "#000",
              fontSize: 16,
              fontFamily: "黑体",
            },
          },
          series: [
            {
              // name: "Access From",
              type: "pie",
              radius: ["30%", "55%"],
              avoidLabelOverlap: false, //单行标签会自动避免重叠
              minShowLabelAngle: 10, //多行标签 最小标签角度设置为10
              label: {
                show: true,
                formatter: function (param) {
                  if (param.value == "0") {
                    return;
                  } else {
                    return param.name + param.value;
                  }
                },
              },
              center: ["50%", "55%"],
              emphasis: {
                label: {
                  show: true,
                },
              },
              labelLine: {
                show: true,
              },
              data: [],
            },
          ],
        });
      },
      getdata() {
        getDataApiStatistic().then((response) => {
          if (response.code === 200) {
          const statusCode = JSON.parse(JSON.stringify(response.data).replace(/statusCode/g, "name"));
          const list = JSON.parse(JSON.stringify(statusCode).replace(/statuscount/g, "value"));
          // console.log(list);
          list.forEach(element => {
            if(element.name===1){
              element.name = '待发布'
            }else if(element.name===2){
              element.name = '已发布'
            }else{
              element.name = '已下线'
            }
          });
            this.chart.setOption({
              series: [
                {
                  data: list,
                },
              ],
            });
          } else {
            this.chart.setOption({
              series: [
                {
                  data: [],
                },
              ],
            });
          }
        });
      },
  
  //窗口自适应
      resize() {
        if (this.resizeTimer) {
          clearTimeout(this.resizeTimer);
        }
        this.resizeTimer = setTimeout(() => {
          let chart = echarts.getInstanceByDom(this.$refs.chart);
          chart.resize();
        }, 10);
      },
    },
  };
  </script>
  
  <style scoped>
  .chart {
    width: 100%;
    height: 100%;
    display: block;
    margin: 0 auto;
  }
  
  </style>
  

2、新版本
main.js

import * as echarts from 'echarts'
Vue.prototype.$echarts = echarts

组件template

<template>
  <div
      class="chart"
      v-loading="loading"
      element-loading-background="rgba(0, 0, 0, 0)"
  >
    <div ref="chart" class="chart" :style="{visibility:loading?'hidden':'visible'}"></div>
  </div>
</template>
<script>
export default {
  name: 'FlowChart',
  data() {
    return {
      resizeTimer: null,
      dataCount: 0,
      chart: null,
      loading: true,
      keys: [0, 0, 0],
    }
  },
  computed: {
    update() {
      return [
        this.$store.state.topology.link.key,
        this.$store.state.linkPerformance.key,
        this.$store.state.linkFlow.key,
      ]
    },
    displayIpv4() {
      return this.$store.state.topology.displayIpv4
    },
  },
  watch: {
    update(_new) {
      if (this.checkUpdate(this.keys, _new)) {
        this.setLinkData(this.displayIpv4 ? this.$store.getters.link : this.$store.getters.ipv6Link)
        this.keys = [..._new]
      }
    },
  },
  mounted() {
     window.addEventListener('resize', this.resize)
    this.chart = this.$echarts.init(this.$refs.chart)
    this.draw()
  },
  beforeDestroy() {
     window.removeEventListener('resize', this.resize)
    this.chart.dispose()
  },
  methods: {
    // 绘图
    draw() {
      try {
        this.chart.clear()
        this.chart.setOption({
          color: ['#5AB1EF'],
          tooltip: {
            show: true,
            trigger: 'item',
            showDelay: 0, // 浮窗显示延时
            hideDelay: 0, // 浮窗隐藏延时
            transitionDuration: 0, // 提示框浮层的移动动画过渡时间,单位是 s,设置为 0 的时候会紧跟着鼠标移动
            backgroundColor: 'rgba(0, 0, 0, 0.7)', // 浮窗背景颜色
            borderWidth: 1,
            borderColor: '#08b1e7',
            textStyle: {
              color: '#fff',
            },
            // 浮窗内文本格式
            formatter: params => {
              return '链路 ' + params.data.name
            },
          },
          grid: {
            top: 10,
            left: 20,
            right: 40,
            bottom: 0,
            containLabel: true,
          },
          dataset: [
            // 原始数据集
            {
              // dimensions: ['type', 'index', 'number', 'flow', null],
              source: [],
            },
          ],
          xAxis: {
            type: 'log',  // 对数轴
            show: true,
            // name: '流量',
            // nameLocation: 'start',
            position: 'top',  // 显示在上方
            logBase: 10,  // 对数底数
            axisLine: {
              lineStyle: {
                color: 'white',
              },
            },
            splitLine: {
              lineStyle: {
                color: 'grey',
              },
            },
          },
          yAxis: {
            type: 'category',
            inverse: true,
            // animationDuration: 300,
            // animationDurationUpdate: 300,
            axisLabel: {
              show: false,
              // color: 'white',
              // fontSize: '14',
              // formatter: '链路{value}',
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
              interval: 0,
            },
          },
          series: [{
            type: 'bar',
            encode: { x: 'realtimeBandwidth' },
            datasetIndex: 1,
            // realtimeSort: true,
            barWidth: 14, // 柱宽度
            label: {
              show: true, // 开启显示
              position: 'right', // 在右侧显示
              // distance: 5, // 距离图形元素的距离
              // verticalAlign: 'middle',
              color: 'white',
              fontSize: 14,
            },
            itemStyle: {
              borderRadius: [0, 10, 10, 0],
            },
          }],
        })
        // 图标元素点击
        this.chart.on('click', params => {
          // 事件类型dialog:弹窗
          this.$store.commit('setLinkDialogId', params.data.linkId)
        })
        this.chart.on('mouseover', params => {
          this.$store.commit('setHighlightLink', params.data.index)
        })
        this.chart.on('mouseout', params => {
          this.$store.commit('setHighlightLink', -1)
        })
      } catch (err) {
        console.log(err)
      }
    },

    // set数据
    setLinkData(data) {
      // 根据有没有数据显示loading效果
      this.loading = data.length === 0
      const newData = []
      data.forEach(element => {
        if (element.realtimeBandwidth !== undefined)
            // if (['2001::ffff:5->2001::ffff:6',
            //   '2001::ffff:2e->2001::ffff:2d',
            //   '2001::ffff:32->2001::ffff:31',
            //   '2001::ffff:29->2001::ffff:2a',
            //   '2001::ffff:1e->2001::ffff:1d'].includes(element.name))
          newData.push(element)
      })
      // 判断是否需要重绘以适应尺寸
      if (newData.length !== this.dataCount) {
        this.dataCount = newData.length
        // 调整容器尺寸
        this.$refs.chart.style.height = this.dataCount * 40 + 'px'
        // 重绘canvas
        this.chart.resize()
      }
      try {
        if (newData.length === 0) {
          this.chart.setOption({ dataset: [{ source: newData }] })
          return
        }
        this.chart.setOption({
          dataset: [
            {
              source: newData,
            },
            {
              transform: {
                type: 'sort',
                config: { dimension: 'realtimeBandwidth', order: 'desc' },
              },
            },
          ],
        })
      } catch (echartsErr) {
        console.error(echartsErr)
      }
    },

    // 监听窗口resize事件,重绘canvas
    resize() {
      if (this.resizeTimer) {
        clearTimeout(this.resizeTimer)
      }
      this.resizeTimer = setTimeout(() => {
        this.$echarts.getInstanceByDom(this.$refs.chart).resize()
      }, 200)
    },

    // 数据更新检查,判断两个key数组的元素是否均不相同
    checkUpdate(a, b) {
      for (let i = 0; i < a.length; i++) {
        if (a[i] === b[i]) return false
      }
      return true
    },
  },
}
</script>


<style scoped>
.chart {
  width: 100%;
  height: 100%;
  display: block;
  margin: 0 auto;
}
</style>

你可能感兴趣的:(echarts,vue.js,javascript)