在vue中即使使用v-if依旧无法清除echarts的dom节点,此时我们要用到echarts提供的销毁实例的方法 dispose
<template>
<div style="padding: 50px;">
<Button type="primary" @click="switchChat">图表切换</Button>
<div style="margin-top: 50px;border: 1px solid #eee;padding:30px;">
<div v-if="isShowPieChat" id="pieChat" style="min-width:900px;height:600px;"></div>
<div v-else id="lineChat" style="min-width:900px;height:600px;"></div>
</div>
</div>
</template>
<script>
import * as echarts from 'echarts';
export default {
name: "echarts4",
data() {
return {
myPieChat:"",
myLineChat:"",
isShowPieChat:true,
}
},
mounted(){
this.initPieChart();
},
methods:{
initPieChart(){
this.myPieChat = echarts.init(document.getElementById('pieChat'))
let option = {
title: {
text: 'Referer of a Website',
subtext: 'Fake Data',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: 'Access From',
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
option && this.myPieChat.setOption(option);
},
initLineChart(){
this.myLineChat = echarts.init(document.getElementById('lineChat'));
let option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value',
axisLine: { // 是否展示Y轴的竖线,
show: true,
lineStyle: {
color: "black" // 设置Y轴的颜色
}
},
},
series: [
{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}
]
};
option && this.myLineChat.setOption(option);
},
switchChat() {
// 如果直接使用v-if切换的话,不会清除echarts的dom的,当从折线图切换成饼图的时候,会有折线的坐标轴
this.myPieChat && this.myPieChat.dispose(); // echarts使用dispose方法销毁实例
this.myLineChat && this.myLineChat.dispose(); // echarts使用dispose方法销毁实例
this.isShowPieChat = !this.isShowPieChat;
if(this.isShowPieChat) {
this.$nextTick(()=>{
this.initPieChart();
})
} else {
this.$nextTick(()=>{
this.initLineChart();
})
}
}
}
}
</script>
<style scoped>
</style>