元のリンク: Vue で Echarts を使用するときに、dom 上ですでに初期化されているチャート インスタンスがあるという警告問題を解決する
問題の説明
これを使用すると、複数回ロードした後にこの黄色の警告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.
親コンポーネントのコード:
const taskDetailDom = ref()
const open = ()=> {
if (taskDetailDom.value) {
taskDetailDom.value.initEchart()
}
}
どうやって?ここではサブコンポーネントの記述のみが異なります。
進入禁止:
<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"
を参照) は次のとおりです。
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()
。
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
})