Vue3.0引入Echarts并使用

  • Post author:
  • Post category:vue


本文主要总结Vue3.0 中全局引用echarts及封装的公共方法。封装的公共方法参考

这里

(感恩.gif)



一、Vue3.0全局引入Echarts



1. 安装echarts

npm install echarts --save



2. main.js引入echarts

// 引入 echarts
import * as echarts from "echarts";
const app = createApp(App);
// 全局挂载 echarts
app.config.globalProperties.$echarts = echarts;



3. vue文件里使用

<template>
  <div
    ref="lineChart"
    id="lineChart"
    :style="{ width: '800px', height: '400px' }"
  ></div>
</template>

<script>
import { getCurrentInstance, onMounted } from "vue";
export default {
  setup() {
    // 通过 internalInstance.appContext.config.globalProperties 获取全局属性或方法
    let internalInstance = getCurrentInstance();
    let echarts = internalInstance.appContext.config.globalProperties.$echarts;

    onMounted(() => {
      const dom = document.getElementById("lineChart");
      const myChart = echarts.init(dom); // 初始化echarts实例
      const option = {···}; // 图表配置参数
      myChart.setOption(option);
      // 设置实例参数
      window.onresize = () => {
        myChart.resize();
      };
    });
    return {};
  },
};
</script>



二、Vue3.0 封装echarts公共方法

使用Echarts做数据大屏的时候,需要初始化多个图表,每个图表的都要进行初始化对应的DOM元素绑定var myChart = echarts.init(document.getElementById(‘eleDom’));封装一个公共方法比较方便。



1. 在utility目录下建立initEcharts.js文件

// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from "echarts/core";
// 引入各种图表,图表后缀都为 Chart
import { BarChart, PieChart, LineChart } from "echarts/charts";
// 引入提示框,标题,直角坐标系等组件,组件后缀都为 Component
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  // GeoCoComponent
} from "echarts/components";
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from "echarts/renderers";

// DIV 宽高变化监听
import { EleResize } from "@/utility/eleResize";

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  PieChart,
  LineChart,
  CanvasRenderer,
]);

/** 封装 echart初始化方法,需要传入 绘制图表的dom元素和绘制图表缩需要的相关配置项 *
 *   同时还添加了图表自动适应dom的宽高变化的功能,需要引入EleResize.js
 */
function drawChart(dom, option) {
  const $Chart = echarts.init(document.getElementById(dom));
  const resizeDiv = document.getElementById(dom);
  $Chart.setOption(option);
  const listener = function () {
    console.log("divRsize");
    $Chart.resize();
  };
  EleResize.on(resizeDiv, listener);
  return $Chart;
}

export { drawChart };



2. main.js

// 引入封装好的初始化方法
import { drawChart } from "@/utility/initEcharts";
// 在vue的原型上绑上 刚刚封装的方法,将来可以在组件中通过this.$drawChart()来进行调用
const app = createApp(App);
app.config.globalProperties.$drawChart = drawChart;



3. 在vue文件中使用

只需要配置

option

即可

<template>
   <div
     ref="lineChart"
     id="lineChart"
     :style="{ width: '800px', height: '400px' }"
   ></div>
</template>

<script>
const domEle = "lineChart";
// 图表配置项
const option = {···};
export default {
  mounted() {
    this.darwChart();
  },
  data() {
    return {
      lineChart: null,
    };
  },
  methods: {
    darwChart() {
	  this.lineChart = this.$drawChart(domEle, option);
    },
  },
};
</script>



4. JS监听div的resize事件EleResize.js


EleResize.js

var EleResize = {
  _handleResize: function(e) {
    var ele = e.target || e.srcElement
    var trigger = ele.__resizeTrigger__
    if (trigger) {
      var handlers = trigger.__z_resizeListeners
      if (handlers) {
        var size = handlers.length
        for (var i = 0; i < size; i++) {
          var h = handlers[i]
          var handler = h.handler
          var context = h.context
          handler.apply(context, [e])
        }
      }
    }
  },
  _removeHandler: function(ele, handler, context) {
    var handlers = ele.__z_resizeListeners
    if (handlers) {
      var size = handlers.length
      for (var i = 0; i < size; i++) {
        var h = handlers[i]
        if (h.handler === handler && h.context === context) {
          handlers.splice(i, 1)
          return
        }
      }
    }
  },
  _createResizeTrigger: function(ele) {
    var obj = document.createElement('object')
    obj.setAttribute(
      'style',
      'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden;opacity: 0; pointer-events: none; z-index: -1;'
    )
    obj.onload = EleResize._handleObjectLoad
    obj.type = 'text/html'
    ele.appendChild(obj)
    obj.data = 'about:blank'
    return obj
  },
  _handleObjectLoad: function(evt) {
    this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__
    this.contentDocument.defaultView.addEventListener(
      'resize',
      EleResize._handleResize
    )
  }
}
if (document.attachEvent) {
  // ie9-10
  EleResize.on = function(ele, handler, context) {
    var handlers = ele.__z_resizeListeners
    if (!handlers) {
      handlers = []
      ele.__z_resizeListeners = handlers
      ele.__resizeTrigger__ = ele
      ele.attachEvent('onresize', EleResize._handleResize)
    }
    handlers.push({
      handler: handler,
      context: context
    })
  }
  EleResize.off = function(ele, handler, context) {
    var handlers = ele.__z_resizeListeners
    if (handlers) {
      EleResize._removeHandler(ele, handler, context)
      if (handlers.length === 0) {
        ele.detachEvent('onresize', EleResize._handleResize)
        delete ele.__z_resizeListeners
      }
    }
  }
} else {
  EleResize.on = function(ele, handler, context) {
    var handlers = ele.__z_resizeListeners
    if (!handlers) {
      handlers = []
      ele.__z_resizeListeners = handlers

      if (getComputedStyle(ele, null).position === 'static') {
        ele.style.position = 'relative'
      }
      var obj = EleResize._createResizeTrigger(ele)
      ele.__resizeTrigger__ = obj
      obj.__resizeElement__ = ele
    }
    handlers.push({
      handler: handler,
      context: context
    })
  }
  EleResize.off = function(ele, handler, context) {
    var handlers = ele.__z_resizeListeners
    if (handlers) {
      EleResize._removeHandler(ele, handler, context)
      if (handlers.length === 0) {
        var trigger = ele.__resizeTrigger__
        if (trigger) {
          trigger.contentDocument.defaultView.removeEventListener(
            'resize',
            EleResize._handleResize
          )
          ele.removeChild(trigger)
          delete ele.__resizeTrigger__
        }
        delete ele.__z_resizeListeners
      }
    }
  }
}
export { EleResize }



版权声明:本文为onepiece1991原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。