这个方法可以解决所有vue中的echarts图例的resize(在需要的vue页面import js,并在需要的div中添加事件即可),连tab的影响也能解决,同时window大小发生变化时也会resize
再也不用到处写resize了
1、安装element-resize-detector依赖
2.新建chart.resize.js文件,添加下面代码

import echarts from 'echarts';
import Vue from 'vue';
import elementResizeDetectorMaker from "element-resize-detector"

export var version = '0.0.1';
var compatible = (/^2\./).test(Vue.version);
if (!compatible) {
    Vue.util.warn('vue echarts resize directive ' + version + ' only supports Vue 2.x, and does not support Vue ' + Vue.version);
}
let HANDLER = "_vue_echarts_resize_handler"

function bind(el) {
    unbind(el);
    el[HANDLER] = function () {
        let chart = echarts.getInstanceByDom(el);
        if (!chart) {
            return;
        }
        chart.resize();
    }
    //监听window窗体变化,更新echarts大小
    //window.addEventListener("resize", el[HANDLER])
    //监听绑定的div大小变化,更新echarts大小
    elementResizeDetectorMaker().listenTo(el,el[HANDLER])
    
}
function unbind(el) {
    //window.removeEventListener("resize", el[HANDLER]);
    elementResizeDetectorMaker().removeListener(el,el[HANDLER])
    delete el[HANDLER];
}
var directive = {
    bind: bind,
    unbind: unbind
};
Vue.directive("on-echart-resize", directive)

3.vue代码

<template>
<div id="chart1" v-on-echart-resize></div>
</template>
<script>
import "@/chart.resize";
export default {
name: "resize_test",
  data() {
    return {
      chart1: null
    };
  },
  mounted: function() {
     if (this.chart1 === null) {
        this.$set(
          this,
          "chart1",
          this.$echarts.init(
            document.getElementById("chart1")
          )
        );
     this.setChart1({});
  }
};
</script>

这是通过学习并结合这两个网址实现的功能
https://juejin.im/post/5aa3b2046fb9a028ce7b36c7
https://blog.csdn.net/csl125/article/details/89245267

Logo

前往低代码交流专区

更多推荐