本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

##Vue中使用Axios动态加载数据到Echarts_为何图表始终为空白?

网络教程 app 1℃

##Vue中使用Axios动态加载数据到Echarts_为何图表始终为空白

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(‘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,为何图表始终为空白?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » ##Vue中使用Axios动态加载数据到Echarts_为何图表始终为空白?

喜欢 (0)