
vue 中使用 axios 动态加载数据到 echarts 中
在 vue.js 应用中,想通过 axios 从 php 后端获取数据并展示在 echarts 中,但出现数据显示失败的问题。
问题描述
根据提供的代码,可以看出开发者已设置了 echarts 实例并定义了加载数据的 mounted 生命周期函数,并在其中调用了 drawline 方法。此方法负责向一个基于 php 的后端进行 axios get 请求,并将响应数据解析到 x_city 和 y_people 数据属性中。
立即学习“前端免费学习笔记(深入)”;
问题解决
然而,解决问题的关键在于代码中存在两个问题:
arrtest 函数的放置位置:arrtest 函数不应在 mounted 函数内,而应移动到 methods 对象中。将其包含在 methods 内可以确保函数始终在该组件实例的上下文中执行。数据加载和图表渲染的时机:drawline 方法中,需要在 axios 请求成功后再调用 mychart.setoption(option) 来渲染图表。目前,setoption 操作正在尝试使用未加载的数据执行,从而导致图表为空白。
解决后的代码如下:
export default { data(){ return{ x_city:[], y_people:[] } }, mounted() { this.drawLine(); }, methods: { drawLine() { let myChart = echarts.init(document.getElementById('myChart')) let that = this; function arrtest(){ axios.get('http://localhost:3000/src/statics/test1.php').then((res) => { console.log(res.data) 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(); // 确保数据加载后再渲染图表 }) } arrtest() 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) } }}
通过这些更改,arrtest 函数首先会在 axios 请求成功后被调用并解析数据,然后 drawline 方法会立即调用以渲染图表,确保数据加载后才显示。
以上就是## Vue 中使用 Axios 动态加载数据到 Echarts,为何图表始终为空白?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1248728.html
微信扫一扫
支付宝扫一扫