解决vue3中echarts图表在页面刷新后无法自适应改变大小问题

1,221 阅读1分钟

一、将echarts变量独立出来

let myChart: echarts.ECharts | null = null

二 、创建echarts图表显示方法

const showEcharts = () => {
  // 基于准备好的dom,初始化echarts实例
  if (!myChart) {
    var chartDom = document.getElementById('echarts')
    myChart = echarts.init(chartDom)
  }
  option && myChart.setOption(option)
}

三、设置resize刷新函数

需要添加监听和移除监听窗口大小的变化,避免性能问题,必须要保证能移除

// 设置resize函数 不能用箭头函数因为不知道内存地址无法remove,必须定义出来
const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}

四、添加窗口大小变化监听和移除监听

onMounted(() => {
  showEcharts ()
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
})