0
点赞
收藏
分享

微信扫一扫

Vue封装echarts组件

何以至千里 2021-09-30 阅读 55
Vue脚手架

1、最近做的项目是后台管理系统,里面含有各种的echarts的图标,一般的图表都是比较好绘制的,稍微比较难的世界地图和中国地图的绘制。
在vue中引入echarts,分两种情况引入,一种值npm安装包,另一种是cdn外部引入,但是这个对于一般的echarts绘制是没有影响的。
首先安装echarts依赖

npm install echarts -S 

你可选择全局导入,也可以在需要的页面导入。全局的话,在main.js里面,然后就可以变成全局的了,就不需要在局部引进echarts了



我是封装的组件

<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: {
      // 监听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() {
    // 设置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) {
      /* 根据表格数据设置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"
            />


var color = ['#FA5882', '#dcbf71']
// 设置圆点
      // 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: {
                // 每个区域的样式
                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 // 波纹圆环最大限制,值越大波纹越大
                },
                label: {
                  normal: {
                    // 默认的文本标签显示样式
                    show: true,
                    position: 'top', // 标签显示的位置
                    formatter: '{b}' // 标签内容格式器
                  }
                },
                itemStyle: {
                  normal: {
                    color: color[0]
                  }
                },
                data: ZZData.map(function(dataItem) {
                  return {
                    name: dataItem[1].name,
                    value: GeoCoordMap[dataItem[1].name], // 起点的位置
                    symbolSize: dataItem[1].value // 散点的大小,通过之前设置的权重来计算,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'],   // 用于设置箭头
              //   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)    // 特效的起始、终点位置,一个二维数组,相当于coords: convertData(item[1])
              // },
            ]
          }

最后利用混合混入,实现图表自适应的效果

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() {
    //离开当前页面清除定时器 及事件监听
    if(this.interval){
      clearInterval(this.interval);
    }
    let _this = this;
    window.removeEventListener('resize', _this.resizeHandel);
  }
};

世界地图的绘制####

中国地图的绘制####

举报

相关推荐

0 条评论