Vue封裝echarts組件

1、最近做的項目是后臺管理系統(tǒng),里面含有各種的echarts的圖標,一般的圖表都是比較好繪制的,稍微比較難的世界地圖和中國地圖的繪制。
在vue中引入echarts,分兩種情況引入,一種值npm安裝包,另一種是cdn外部引入,但是這個對于一般的echarts繪制是沒有影響的。
首先安裝echarts依賴

npm install echarts -S 

你可選擇全局導(dǎo)入,也可以在需要的頁面導(dǎo)入。全局的話,在main.js里面,然后就可以變成全局的了,就不需要在局部引進echarts了

image.png

image.png

我是封裝的組件

<template>
  <div
    :id="id"
    :style="{
      width: chartWidth,
      height: chartHeight,
      float: 'left',
      backgroundImage:
        'url(' +
        (empty == '0'
          ? require('../../../public/img/timg.gif')
          : empty == '1'
            ? require('../../../public/img/empty.png')
            : require('../../../public/img/1.png')) +
        ')',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      backgroundSize: empty == '1' ? 'contain' : 'auto'
    }"
  />
</template>
<script>
/* echarts組件 */
import echarts from 'echarts';
export default {
  props: ['id', 'option', 'chartWidth', 'chartHeight'],
  data() {
    return {
      myChart: {},
      empty: 0
    };
  },
  watch: {
    option: {
      // 監(jiān)聽option的變化
      handler: function(newData, oldData) {
        if (JSON.stringify(newData) === JSON.stringify({})) {
          this.empty = '0';
        } else if (
          newData.series[0].data.length === 0 &&
          newData.series[0].type !== 'map'
        ) {
          this.empty = '1';
        } else {
          this.empty = '2';
        }
        this.myChart = echarts.init(document.getElementById(this.id));
        this.myChart.setOption(newData);
        this.$emit('toParent', this.myChart, this.chartWidth, this.id);
      },
      deep: true
    }
  },
  mounted() {
    // 設(shè)置echarts的寬度
    var chart = document.getElementById(this.id);
    if (this.chartWidth.indexOf('px') !== -1) {
      chart.style.width = this.chartWidth;
    } else {
      chart.style.width =
        ((window.innerWidth -
          (this.$store.state.app.sidebar.opened ? 280 : 150)) *
          this.chartWidth.slice(0, this.chartWidth.length - 1)) /
          100 +
        'px';
    }
    if (this.option) {
      /* 根據(jù)表格數(shù)據(jù)設(shè)置echarts背景圖*/
      if (Object.keys(this.option).length !== 0) {
        if (JSON.stringify(this.option) === JSON.stringify({})) {
          this.empty = '0';
        } else if (
          this.option.series[0].data.length === 0 &&
          this.option.series[0].type !== 'map'
        ) {
          this.empty = '1';
        } else {
          this.empty = '2';
        }
        this.myChart = echarts.init(document.getElementById(this.id));
        this.myChart.setOption(this.option);
        this.$emit('toParent', this.myChart, this.chartWidth, this.id);
      }
    }
  }
};
</script>

頁面引用

 <Echarts
              :id="'idWord'"
              :chart-height="'100%'"
              :chart-width="'50%'"
              :option="mapWord"
              @toParent="getEcharts"
            />
image.png

image.png
var color = ['#FA5882', '#dcbf71']
// 設(shè)置圓點
      // var points = [
      //         {name:'河南',value: [118.8062, 31.9208],itemStyle:{color:'#DCBF71'}}
      // ]
 echarts.registerMap('world', countryGeo) **npm安裝的這個是重點**
  this.mapWord = {
            backgroundColor: '#fff',
            geo: {
              map: 'world', // 與引用進來的地圖js名字一致
              roam: false, // 禁止縮放平移
              label: {
                // 隱藏地名
                show: false,
                emphasis: {
                  show: true
                }
              },
              itemStyle: {
                // 每個區(qū)域的樣式
                normal: {
                  areaColor: '#44A9E1',
                  borderWidth: 0.5,
                  borderColor: '#fff',
                  borderType: 'solid'
                },
                emphasis: {
                  areaColor: '#7151E5',
                  label: {
                    show: false,
                    color: '#7151E5'
                  }
                }
              }
            },
            series: [
              // 漣漪圖 // 散點效果
              {
                type: 'effectScatter',
                coordinateSystem: 'geo', // 表示使用的坐標系為地理坐標系
                zlevel: 2,
                rippleEffect: {
                  period: 2, // 動畫時間,值越小速度越快
                  brushType: 'stroke', // 波紋繪制方式 stroke, fill
                  scale: 5 // 波紋圓環(huán)最大限制,值越大波紋越大
                },
                label: {
                  normal: {
                    // 默認的文本標簽顯示樣式
                    show: true,
                    position: 'top', // 標簽顯示的位置
                    formatter: '' // 標簽內(nèi)容格式器
                  }
                },
                itemStyle: {
                  normal: {
                    color: color[0]
                  }
                },
                data: ZZData.map(function(dataItem) {
                  return {
                    name: dataItem[1].name,
                    value: GeoCoordMap[dataItem[1].name], // 起點的位置
                    symbolSize: dataItem[1].value // 散點的大小,通過之前設(shè)置的權(quán)重來計算,val的值來自data返回的value
                  }
                })
              },
              // 地圖線的動畫效果
              {
                // 白色航線特效圖
                type: 'lines',
                zlevel: 1, // 用于分層,z-index的效果
                effect: {
                  show: true, // 動效是否顯示
                  period: 2, // 特效動畫時間
                  trailLength: 0.2, // 特效尾跡的長度
                  // symbol: 'arrow', //箭頭圖標
                  color: '#fff', // 特效顏色
                  symbolSize: 5 // 特效大小
                },
                lineStyle: {
                  normal: {
                    // 正常情況下的線條樣式
                    color: '#FA5882',
                    width: 0, // 因為是疊加效果,要是有寬度,線條會變粗,白色航線特效不明顯
                    opacity: 1, // 尾跡線條透明度
                    curveness: -0.3 // 線條曲度
                  }
                },
                data: this.convertData(this.points) // 特效的起始、終點位置
              }
              // 小飛機航線效果
              // {
              //   type: 'lines',
              //   zlevel: 2,
              //   symbol: ['none', 'arrow'],   // 用于設(shè)置箭頭
              //   symbolSize: 10,
              //   effect: {
              //     show: true,
              //     period: 6,
              //     trailLength: 0,
              //     symbol: 'pin',         // 特效形狀,可以用其他svg pathdata路徑代替
              //     symbolSize: 1
              //   },
              //   lineStyle: {
              //     normal: {
              //       color: '#dcbf71',
              //       width: 1,
              //       opacity: 0.6,
              //       curveness: -0.2
              //     }
              //   },
              //   data:this.convertData(this.data)    // 特效的起始、終點位置,一個二維數(shù)組,相當于coords: convertData(item[1])
              // },
            ]
          }

最后利用混合混入,實現(xiàn)圖表自適應(yīng)的效果

export const resizeEcharts = {
  watch: {
    '$store.state.cutWidth': {
      handler(newData, oldData) {
        this.resizeHandel();
      },
      deep: true
    }
  },
  methods: {
    resizeHandel() {
      for (var i = 0; i < this.echarts.length; i++) {
        var chart = document.getElementById(this.echarts[i].id);
        if (chart) {
          if (this.echarts[i].width.indexOf('px') !== -1) {
            chart.style.width = this.echarts[i].width;
          } else {
            chart.style.width =
              ((window.innerWidth - this.$store.state.cutWidth) *
                this.echarts[i].width.slice(
                  0,
                  this.echarts[i].width.length - 1
                )) /
                100 +
              'px';
          }
        }
        this.echarts[i].echart.resize();
      }
    },
    getEcharts(echart, width, id) {
      this.echarts.push({ echart: echart, id: id, width: width });
      let _this = this;
      window.addEventListener('resize', _this.resizeHandel);
    }
  },
  beforeDestroy() {
    //離開當前頁面清除定時器 及事件監(jiān)聽
    if(this.interval){
      clearInterval(this.interval);
    }
    let _this = this;
    window.removeEventListener('resize', _this.resizeHandel);
  }
};

世界地圖的繪制####

image.png

中國地圖的繪制####

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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