vue项目 Echarts[警告]There is a chart instance already initialized on the dom.「已解决」

650 阅读1分钟

image.png

  • 报错信息:There is a chart instance already initialized on the dom.

  • 出现的问题:页面上Echart图区域空白

  • 复现方式:Echarts页面加载完成后切换到其他页面,再重新回到该页面。

  • 原因:Echarts图指定的dom容器已经初始化,实例已存在。但是这时再对这个容器进行重新渲染时,需要判断实例是否存在,若存在需先销毁再渲染

代码如下:

let stateChartDom = null // 渲染容器,注意等于[]时会报错
const stateChart = async () => {
  const chartDom = document.getElementById('Echart') // 判断实例是否已经存在
  if (chartDom && chartDom.getAttribute('_echarts_instance_')) {
    echarts.dispose(chartDom) // 若存在先销毁
  }
  stateChartDom = echarts.init(chartDom)
  const option = {
      ……
  }
  option && stateChartDom.setOption(option)
}