用echarts时,多次加载就会报存在警告,意思是DOM上已经初始化了一个图表实例。处理方法删除DOM:
echarts.dispose(document.getElementById(id))
用echarts时,如果不存在DOM,就会报错,处理方法先检查是否DOM存在:
if (document.getElementById(id) == null) {
return
}
最终代码
//1,下载echarts
npm i echarts -S
//2,在main.js中引入echarts
import * as echarts from "echarts";
//3,html
<div v-for="(item, index) in list" :key="index">
<div class="myChart"></div>
</div>
//4,css
.myChart {
width: 100%;
height: 550px;
}
//5,js
mounted() {
//调用接口函数
this.getData();
}
methods:{
getData: function () {
this.$http.get('xxx').then(res => {
//处理数据
this.data = res.data
//再调用图表函数
this.$nextTick(() => {
this.drawChart();
});
}).catch(err => {
console.log(err)
})
},
drawChart:function(){
let item = document.getElementsByClassName("myChart")
for (let i = 0; i < item.length; i++) {
if (item[i] == null) {
return
}
echarts.dispose(item[i])
let myChart = echarts.init(item[i]);
myChart.setOption({})
window.addEventListener("resize", () => { //根据屏幕进行实时绘制
myChart.resize();
});
}
}
}