问题描述

使用echarts的时候,多次加载会出现There is a chart instance already initialized on the dom.这个黄色警告,大概意思就是dom上已经初始化了一个图表实例。此警告信息不影响echarts正常加载,但是有bug不解决的话,心里痒的慌!

先说明一下,echarts是用在了子组件的弹窗里,然后在父组件打开弹窗时调用echarts.init()的初始化方法。第一次渲染正常,之后再打开弹窗控制台就会报There is a chart instance already initialized on the dom.

父组件中的代码:

1
2
3
4
5
6
const taskDetailDom = ref()
const open = ()=> {
if (taskDetailDom.value) {
taskDetailDom.value.initEchart()
}
}

如何造成的? 这里只区别了子组件的写法。

错误写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script setup lang='ts'>
import echarts from "@/utils/custom/echart"

let tChart: Ref<HTMLDivElement | null> = ref(null)
const initEchart = () => {
   const dom = tChart.value
   if (dom) {
      let myChart = echarts.init(dom)
      myChart.setOption(option)
   }
}
defineExpose({
initEchart
})

关于import echarts from "@/utils/custom/echart"此处中的代码(可参考官方示例)如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import * as echarts from 'echarts/core';
import {
BarChart,
LineChart,
PieChart
} from 'echarts/charts';
import {
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
// 数据集组件
DatasetComponent,
// 内置数据转换器组件 (filter, sort)
TransformComponent
} from 'echarts/components';
import { LabelLayout, UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import type {
// 系列类型的定义后缀都为 SeriesOption
BarSeriesOption,
LineSeriesOption
} from 'echarts/charts';
import type {
// 组件类型的定义后缀都为 ComponentOption
LegendComponentOption,
TitleComponentOption,
TooltipComponentOption,
GridComponentOption,
DatasetComponentOption
} from 'echarts/components';
import type {
ComposeOption,
} from 'echarts/core';

// 通过 ComposeOption 来组合出一个只有必须组件和图表的 Option 类型
type ECOption = ComposeOption<
| BarSeriesOption
| LegendComponentOption
| LineSeriesOption
| TitleComponentOption
| TooltipComponentOption
| GridComponentOption
| DatasetComponentOption
>;

// 注册必须的组件
echarts.use([
LegendComponent,
TitleComponent,
TooltipComponent,
GridComponent,
DatasetComponent,
TransformComponent,
BarChart,
LineChart,
PieChart,
LabelLayout,
UniversalTransition,
CanvasRenderer
]);

export default echarts;

解决方法

在方法最外层定义echarts dom对象,然后echarts.init()之前,判断dom是否为空或未定义,如果已存在则调用dispose()方法销毁,再初始化echarts.init()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let tChart: Ref<HTMLDivElement | null> = ref(null)
let myChart: any // 1. 最外层定义 echarts dom
const initEchart = () => {
const dom = tChart.value
if (dom) {
// 2. 判断 dom 是否为空或未定义
if (myChart != null && myChart != "" && myChart != undefined) {
// 3. 已存在则调用 dispose() 方法销毁
myChart.dispose();
}
myChart = echarts.init(dom)
myChart.setOption(option)
}
}
defineExpose({
initEchart
})