gpt4 book ai didi

javascript - VueJS 应用程序将 GET 请求中的数据放入数组中

转载 作者:行者123 更新时间:2023-12-02 22:22:48 25 4
gpt4 key购买 nike

这是我的 VueJS 组件脚本,它应该在仪表板内显示数据。

<script>
import { Chart } from "highcharts-vue";
import Highcharts from "highcharts";
import exportingInit from "highcharts/modules/exporting";
//import stockInit from "highcharts/modules/stock";

//stockInit(Highcharts);
exportingInit(Highcharts);

export default {
props: {
partsdata: {
type: Array
}
},
methods: {
fetchData() {
this.$http.get('http://127.0.0.1:5000/data/')
.then(response => {
return response.json();
}).then(data => {
var result = JSON.parse(data) // eslint-disable-line no-console
console.log(result.Fare) // eslint-disable-line no-console
})
}
},
components: {
highcharts: Chart
},

data() {
return {
chartOptions: {
series: [{
data: [] // sample data
}]
}
}
}
};
</script>

从我的后端接收数据工作正常,但我无法将其放入图表中。我仍然在努力如何处理异步任务,所以我尝试了这个但失败了

this.data.push(result.Fare)

Header.vue?5e07:33 Uncaught (in promise) TypeError: Cannot read property 'push' of undefined at VueComponent.eval (Header.vue?5e07:34)

谁能告诉我该怎么做?

更新:这是我触发方法的模板:

<template>
<div>
<button @click="fetchData" class="btn-primary">Get Data</button>
<highcharts
:options="chartOptions"
></highcharts>

</div>
</template>

最佳答案

如果您正在尝试this.data.push,请查看您的代码,它告诉您其未定义,这是可以理解的。要在 fetchData 方法中获取 data 属性,您必须使用this.chartOptions.series[0].data.push我不确定您在该代码中的何处触发 fetchData 。尝试将其移至 vue 生命周期中创建/安装的方法,然后您可以将 ChartOptions 更改为计算或观察者,在 data() 方法中设置数据并使用 this.data 在 ChartOptions 中调用它。

更新:单击时对于您的获取请求来说很好,如果它触发保持不变,那么您设置它的位置就是问题所在。我重构了你的请求,如果它成功,当你测试它时,response.data 应该给你你需要的结果,不知道为什么你需要解析它,除非它返回一个 json blob 作为字符串?我还在图表渲染器中添加了一个 v-if ,如果 this.data 为空则不渲染。看看你的进展如何。

import { Chart } from "highcharts-vue";
import Highcharts from "highcharts";
import exportingInit from "highcharts/modules/exporting";
//import stockInit from "highcharts/modules/stock";

//stockInit(Highcharts);
exportingInit(Highcharts);

export default {
props: {
partsdata: {
type: Array
}
},
methods: {
fetchData() {
this.$http.get('http://127.0.0.1:5000/data/')
.then(response => {
this.data.push(JSON.parse(response.data))
})
}
},
watch: {
data: function() {
this.chartOptions.series[0].data.push(this.data)
}

},
components: {
highcharts: Chart
},

data() {
return {
data: [],
chartOptions: {
series: [{
data: [] // sample data
}]
}
}
}
};
</script>
    <template>
<div>
<button @click="fetchData" class="btn-primary">Get Data</button>
<highcharts if="data.length > 0" :options="chartOptions" ></highcharts>

</div>
</template>

关于javascript - VueJS 应用程序将 GET 请求中的数据放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com