切换下拉选项生成多幅Apache Echarts时出现初始化问题
解决ECharts「There is a chart instance already initialized on the dom」错误
问题根源
你之前的代码用全局变量myChart追踪实例,存在两个核心问题:
- 全局变量仅能记录一个实例,若多个容器调用该函数,实例会被覆盖;
- 切换图表类型时,无法精准判断当前目标容器上是否已存在实例,导致重复初始化报错。
ECharts官方推荐通过DOM元素直接获取对应实例,而非依赖全局变量。
修正方案
修改独立.js文件中的createChartLineCat函数,使用echarts.getInstanceByDom获取目标容器的已有实例,再进行销毁/重建操作:
someNameECharts.createChartLineCat = function(config) { // 获取目标DOM容器 const dom = document.getElementById(config.bindTo); if (!dom) return; // 容器不存在则直接返回 // 检查容器上是否已有图表实例 const existingChart = echarts.getInstanceByDom(dom); if (existingChart) { existingChart.dispose(); // 销毁已有实例,避免重复初始化 } // 初始化新的图表实例 const myChart = echarts.init(dom, null, {width: config.width, height: config.height}); /// 省略部分代码 //// let option = { title: { text: config.title }, toolbox: { feature: { dataZoom: {}, saveAsImage: {}, magicType: { type: ['line', 'bar', 'stack'] } } }, color: colorSchema, dataset: [ { dimensions: [{name: keyNames[0], type:'ordinal'}, {name: keyNames[1]}, {name: keyNames[2]}], source: config.graphData, }, ], tooltip: {}, grid: { width: '70%', left: '3%', right: '4%', bottom: '3%', containLabel: true }, legend: { orient: 'vertical', right: 10, top: 'center', }, xAxis: { type: 'category', }, yAxis: { type: 'value', }, series: seriesSettings }; outputDataset.forEach(function(ds) { option.dataset.push(ds); }); myChart.setOption(option); }
额外说明
- 无需在switch分支中添加
myChart.clear()或清空容器的代码,函数内部已处理实例冲突; - 若图表类型差异较小,可将
dispose()替换为clear()后直接调用setOption,保留实例并更新配置; - 移除原代码中全局的
let myChart声明,避免不必要的全局变量污染。
内容的提问来源于stack exchange,提问作者hacking_mike
相关产品推荐
相关产品推荐

