Echarts 如何防止内存泄漏

Echarts 如何防止内存泄漏

概述

在使用Echarts时是很容易产生内存泄漏的,产生内存泄漏的原因是实例化echarts报表后在销毁组件前没有对echarts的实例进行删除。

代码

// 此段代码建议写在mixin中,在使用echarts时调用即可
beforeDestroy() {
    if (!this.chart) {
        return
    }
    // 在组件销毁前调用dispose函数销毁报表
    this.chart.dispose()
    this.chart = null
}

完整代码

此代码直接使用mixin混入即可,封装了报表自适应和报表销毁功能,在每一个报表组件中引入就好。

import { debounce } from '@/utils/common'

export default {
  data() {
    return {
      $_sidebarElm: null,
      chart: null,
      dataEmpty: false,
    }
  },
  watch: {
    data(newVal) {
      if (!this.chart) {
        this.$_init();
      } else {
        this.setData(newVal);
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.$_init();
    });
    this.$_initResizeEvent()
  },
  beforeDestroy() {
    this.$_disposeChart()
    this.$_destroyResizeEvent()
  },
  activated() {
    this.$_initResizeEvent()
  },
  deactivated() {
    this.$_destroyResizeEvent()
  },
  methods: {
    /**
     * 初始化数据
     */
    $_init() {
      if (this.data && this.data.length === 0) {
        this.dataEmpty = true;
      } else {
        this.dataEmpty = false;
        this.initChart();
        this.setData(this.data);
      }
    },
    $_resizeHandler() {
      return debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)()
    },
    $_initResizeEvent() {
      window.addEventListener('resize', this.$_resizeHandler)
    },
    $_destroyResizeEvent() {
      window.removeEventListener('resize', this.$_resizeHandler)
    },
    // 销毁报表
    $_disposeChart() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    }
  }
}

debounce函数

/**
 * 防抖函数
 * @param {Funciton} fn 函数
 * @param {Number} wait 等待时间
 * @param {immediate} Boolearn 是否立即执行
 */
export function debounce(fn, wait, immediate) {
  let timer
  return function() {
    if (timer) clearTimeout(timer)
    if (immediate) {
      // 如果已经执行过,不再执行
      var callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (callNow) {
        fn.apply(this, arguments)
      }
    } else {
      timer = setTimeout(() => {
        fn.apply(this, arguments)
      }, wait)
    }
  }
}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃土豆丝嗯z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值