vue 中使用 axios 异步请求并渲染 echarts 图表的常见问题
在 vue 项目中,结合 axios 和 echarts 库加载动态数据并展示图表时,可能会遇到数据显示不出的问题。
问题分析:
根据您提供的代码,问题可能出在以下两方面:
解决方案:
要解决这些问题,您可以按照以下步骤进行优化:
以下是对您的代码进行修改的示例:
export default { data() { return { x_city: [], y_people: [], }; }, mounted() { this.arrtest(); }, methods: { arrtest() { let that = this; axios.get('http://localhost:3000/src/statics/test1.php').then((res) => { for (var 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)); } this.drawLine(); }); }, drawLine() { let myChart = echarts.init(document.getElementById('myChart')); let 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); }, }, };
通过对这些修改,您的图表应该能够正确地加载动态数据并进行渲染。