在 vue 中使用 axios 动态获取数据并显示在 echarts 中
在 vue 应用中使用 axios 获取动态数据并将其显示在 echarts 图表中时,有时会出现数据无法显示的问题。要解决此问题,需要对代码进行一些调整。
问题分析
你提供的代码中,在 mounted 生命周期钩子中调用了 drawline 方法,而 arrtest 函数在 methods 对象之外。这会导致 axios 请求在 drawline 方法执行之前发出,导致 mychart 尝试在没有数据的情况下渲染图表。
解决方案
优化后的代码
methods: { drawLine() { const that = this; function arrtest() { 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)); } that.drawLine(); }); } arrtest(); }, drawLine() { // 基于准备好的dom,初始化echarts实例 const myChart = echarts.init(document.getElementById('myChart')); const option = { ... }; myChart.setOption(option); }, },
通过这些调整,可以确保数据在 mychart 渲染图表之前正确加载,从而解决数据无法显示的问题。