vue中echarts图表大小跟随窗口大小自适应的解决方案

项目的需求是ecahrts图表需要跟随窗口自适应。首先第一点想到的就是window.onsize事件去监听。但是我们需要考虑防抖。以下是解决方案。

1. 引入防抖函数

// 防抖函数
// debounce 函数接受一个函数和延迟执行的时间作为参数
export default function debounce (fn, delay) {
  // 维护一个 timer
  let timer = null

  return function () {
    // 获取函数的作用域和变量
    const context = this
    const args = arguments

    clearTimeout(timer)
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

2. 在页面中使用

  • import debounce from '@/utils/debounce'
  • method里添加方法
resizeChart: debounce(function () {
	this.myChart1.resize() // this.myChart1是初始化的图标实例
	this.myChart2.resize()
}, 400)
  • mounted里监听
mounted () {
	window.addEventListener('resize', this.resizeChart)
}
  • beforeDestory里进行销毁
beforeDestroy () {
	window.removeEventListener('resize', this.resizeChart)
},

3. 注意坑!

取消监听resize 事件时必须要和 添加监听resize时传的参数一模一样,否则不起作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值