echarts 初始化 echarts.init(DOMOBJ) 会返回一个 echarts 实例对象,用一个变量接住实例对象就可以生成图表了,例如:
()=>{
let chartDom = document.getElementById('flg')
let timeObj= echarts.init(chartDom);
timeObj.hideLoading()
timeObj.setOption(dataObj);
}
但有些场景下需要将这个实例对象保存下来,例如页面要做自适应,而echarts又需要先销毁才能再重建时,就需要拿到这个实例对象方便销毁。
但是如果将这个实例对象保存在响应式数据上可能会遇到一些不可预料的问题,比如:tooltip 配置失效
实例组件代码如下:
<template>
<div style="width: 300px;height: 300px;border:1px solid pink" id="flg"/>
<div style="width: 300px;height: 300px;border:1px solid pink" id="lineEcharts3"/>
<div style="width: 300px;height: 300px;border:1px solid pink" id="lineEcharts2"/>
<div style="width: 300px;height: 300px;border:1px solid pink" id="lineEcharts1"/>
</template>
<script setup>
import {reactive} from "vue";
import * as echarts from 'echarts/core'
const data = reactive({
echarList:[
{echarExample:null,id:'lineEcharts3'},
{echarExample:null,id:'lineEcharts1'},
{echarExample:null,id:'lineEcharts2'},
],
});
let flgecharExample:null
let dataObj={
"legend": {
"type": "plain",
"icon": "circle",
"itemWidth": 15,
"itemGap": 10,
"top": 16,
"right": 16
},
"grid": {
"top": 50,
"left": 80,
"right": 40,
"bottom": 16
},
"tooltip": {
"trigger": "axis",
"show": true,
"renderMode": "html",
"backgroundColor": "#fff",
"padding": [
12,
16
],
"extraCssText": "box-shadow: 0 0 3px rgba(2, 9, 25, 0.04);",
"textStyle": {
"fontSize": 12,
"color": "#1d2129"
}
},
"xAxis": {
"type": "value",
"axisLine": {
"show": false
},
"axisTick": {
"show": false
},
"axisLabel": {
"show": false
},
"splitLine": {
"show": true,
"lineStyle": {
"type": "dashed",
"width": 1
}
}
},
"yAxis": [
{
"type": "category",
"data": [
"制冷",
"洗涤",
"空调",
"水产业"
],
"axisLine": {
"show": false
},
"axisTick": {
"show": false
},
"axisLabel": {
"show": true,
"color": "#86909C",
"fonSize": 12,
"interval": 0
},
"splitLine": {
"show": false
}
},
{
"data": [
386,
487,
494,
513
],
"axisLine": {
"show": false
},
"axisTick": {
"show": false
},
"axisLabel": {
"color": "#333"
}
}
],
"series": [
{
"name": "产品责任",
"type": "bar",
"barMaxWidth": "13px",
"stack": "total",
"emphasis": {
"disabled": true,
"focus": "series"
},
"data": [
169,
97,
123,
72
]
}
]
}
// 获取数据
const afferent = () => {
// 遍历数组获取数据
data.echarList.forEach(item=>{
let chartDom = document.getElementById(item.id)
item.echarExample = echarts.init(chartDom);
item.echarExample.hideLoading()
item.echarExample.setOption(dataObj);
})
}
setTimeout(()=>{
let chartDom = document.getElementById('flg')
flgecharExample= echarts.init(chartDom);
flgecharExample.hideLoading()
flgecharExample.setOption(dataObj);
},100)
defineExpose({
afferent
});
</script>
上述组件四个图表用的完全相同的配置,唯独实例保存位置一个在reactive 创建的响应式数据内,一个是普通变量却导致除了 flgecharExample 外的三个图表tooltip 失效。
遇到问题的环境:
"vue": "^3.4.27",
"echarts": "^5.5.0"
看csdn 有前辈分析如下:https://blog.csdn.net/weixin_47085255/article/details/132555649
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。