Vue项目中使用Axios和ECharts绘制图表时,图表无法显示,这通常是由于Axios异步请求导致的渲染时机问题。本文将分析并解决此问题,代码示例基于Axios获取PHP数据,并在ECharts中绘制图表。
问题: Axios请求数据完成之后,ECharts图表未能正确渲染,主要原因是ECharts的setOption方法在Axios请求返回数据之前执行,导致数据为空。
原始代码 (存在问题):
<template> <div> <div id="mychart" style="width: 900px; height: 300px;"></div> </div> </template> <script> import * as echarts from 'echarts'; import axios from 'axios'; export default { data() { return { x_city: [], y_people: [] }; }, mounted() { this.drawLine(); }, methods: { drawLine() { let myChart = echarts.init(document.getElementById('mychart')); let that = this; axios.get('http://localhost:3000/src/statics/test1.php') .then((res) => { console.log(res.data); for (let i = 0; i < res.data.length; i++) { that.x_city.push(res.data[i].city); that.y_people.push(parseInt(res.data[i].y_people)); } // 问题在此:setOption在数据获取之前执行 var option = { // ... ECharts 配置 ... }; myChart.setOption(option); }); } } }; </script>
解决方案: 将myChart.setOption(option)方法移入axios.get()的then回调函数中,确保在数据获取完成后再渲染图表。
修改后的代码 (已解决):
<template> <div> <div id="mychart" style="width: 900px; height: 300px;"></div> </div> </template> <script> import * as echarts from 'echarts'; import axios from 'axios'; export default { data() { return { x_city: [], y_people: [] }; }, mounted() { this.drawLine(); }, methods: { drawLine() { let myChart = echarts.init(document.getElementById('mychart')); let that = this; axios.get('http://localhost:3000/src/statics/test1.php') .then((res) => { console.log(res.data); for (let i = 0; i < res.data.length; i++) { that.x_city.push(res.data[i].city); that.y_people.push(parseInt(res.data[i].y_people)); } var option = { tooltip: { show: true }, legend: { data: ['people'] }, xAxis: { type: 'category', data: that.x_city }, yAxis: { type: 'value' }, series: [{ name: 'people', type: 'bar', data: that.y_people }] }; myChart.setOption(option); // 现在在数据获取完成后执行 }); } } }; </script>
通过将setOption方法放在then回调函数内,确保数据已加载完毕再渲染图表,从而解决图表无法显示的问题。 代码中也修正了一些细节,例如使用let代替var,以及更清晰的ECharts配置。 无需额外创建arrtest函数。