(echarts)控制双图表显示隐藏There is a chart instance already initialized on the dom
需求背景:
返回数据中若zAxis、zAxisData字段有值,则显示柱状图,否则显示折线图
<a-card :title="echartTitle" style="width: 100%;" v-show="showLine">
<div class="echartDiv">
<div id="echart" ref="myLineChart" style="height:300px;width:1200px;"></div>
</div>
</a-card>
<a-card :title="echartTitle" style="width: 100%;" v-show="showBar">
<div class="echartDiv">
<div id="echartBar" ref="myLineChartBar" style="height:300px;width:1200px;"></div>
</div>
</a-card>
js:
data(){
return:{
show: true,
cardDiv: true,
myChart: null,
myChartBar: null,
showBar: true,
showLine: true,
...
}
}
//查询
handleSearch() {
this.spinning = true
GetfactoryCompletions({
prompt: this.value,
})
.then((res) => {
this.tableTitle = this.value + ' 如下表所示:'
this.echartTitle = this.value + ' 如下图所示:'
this.spinning = false
if (res.code == 0) {
this.show = false
this.cardDiv = true
...
if (res.resMap.zAxis.length > 0 && res.resMap.zAxisData.length > 0) {
this.showBar = true
this.showLine = false
this.zAxis = res.resMap.zAxis
this.zAxisData = res.resMap.zAxisData
this.$nextTick(() => {
this.graphBar()
})
} else {
this.showLine = true
this.showBar = false
this.xAxis = res.resMap.xAxis
this.xAxisData = res.resMap.xAxisData
this.$nextTick(() => {
this.graph()
})
}
} else {
}
})
.catch((res) => {
})
},
echarts图
//折线图
graph() {
if (this.myChart != null) {
this.myChart.dispose()
}
// 初始化echarts实例
this.myChart = echarts.init(document.getElementById('echart'))
// 绘制图表
let option = {
tooltip: {
trigger: 'axis',
},
xAxis: {
type: 'category',
data: this.xAxisData,
},
yAxis: {
type: 'value',
axisLine: {
show: true,
},
axisTick: {
show: true,
},
},
series: [
{
type: 'line',
data: this.xAxis,
},
],
}
this.myChart.setOption(option)
},
//柱状图
graphBar() {
if (this.myChartBar != null) {
this.myChartBar.dispose()
}
// 初始化echarts实例
this.myChartBar = echarts.init(document.getElementById('echartBar'))
// 绘制图表
let option = {
tooltip: {
trigger: 'axis',
},
title: { text: '' },
legend: {
show: false,
},
xAxis: {
type: 'category',
// data: ['2020', '2021', '2023'],
data: this.zAxisData,
},
yAxis: {
type: 'value',
axisLine: { show: true },
name: '单位(亿方)',
nameTextStyle: {
fontSize: 14,
},
},
series: [
{
name: '平均价格',
type: 'bar',
barWidth: 50, //柱子的粗细
// data: [5000, 10000, 15000],
data: this.zAxis,
label: {
show: true,
position: 'top',
valueAnimation: true,
},
},
],
}
this.myChartBar.setOption(option)
},