总体思路:首先保证series中的data拿到了接口调回来的数据,然后获取新的数据后面再次初始化echarts即调用echarts .init(document.getElementById('mychart')) .setOption(this.option);
数据定义格式——vue2
data() {
return {
// 定义Echarts配置对象
option: {},
}
},
mounted() {
//调用echarts初始化方法
this.initEcharts();
},
beforeDestroy() {
//组件销毁前要注销echarts实例,这一点不是所有场景都必需,但我个人觉得加上无害处
echarts.init(document.getElementById('mychart')).dispose();
},
methods: { initEcharts() { this.option = { title: { text: this.echartsTitle, top: 30, left: 30, textStyle: { fontSize: 18, color: '#707070', }, }, tooltip: { trigger: 'item', textStyle: { fontSize: 14, color: '#707070', align: 'center', }, borderColor: '#707070', formatter: '{b}<br />{d}%', }, legend: { orient: 'vertical', top: '2%', left: '0%', itemWidth: 10, itemHeight: 10, borderRadius: 0, textStyle: { fontSize: 14, }, }, series: [ { type: 'pie', center: ['60%', '50%'], radius: ['40%', '75%'], avoidLabelOverlap: false, itemStyle: { borderRadius: 7, borderColor: '#fff', borderWidth: 3, }, label: { show: false, position: 'outside', }, emphasis: { label: { show: false, fontSize: 40, fontWeight: 'bold', }, }, //data设为空数组,之后调用接口获取数据再赋值。 data: [], }, ], }; const chartDom = document.getElementById('mychart'); const myChart = echarts.init(chartDom); myChart.setOption(this.option); window.addEventListener('resize', () => { myChart.resize(); }); }, //接口调用方法 bjkkPercentRequest() { request({ method: 'GET', url: '/polar/bjkk/data/analysis', }).then((res) => { if (res.status === 200) { if (res.data.code === 200) { let re = []; res.data.data.forEach((item) => { re.push({ value: parseFloat(item.percent), name: item.country }); }); //获取处理之后的数据并赋给echarts this.option.series[0].data = re; //echarts拿到值之后一定要再初始化一遍。数据有更新则后面要再初始化echarts图 echarts .init(document.getElementById('mychart')) .setOption(this.option); } } }); }, },
vue3与vue2思路相同,但要注意区别生命周期函数、vue3的setup形式和vue2的实例形式。
因篇幅问题不能全部显示,请点此查看更多更全内容