![](/img/trans.png)
[英]How to wait for API Call Data before next function is triggered?
[英]Vue wait for API call before loading data
所以我有一個這個 vue 組件,我正在使用 highcharts 並且我有一個 axios API 調用填充測試結果數組。我希望 chartoptions 變量等待 api 調用這是我到目前為止的代碼
<template>
<div>
<highchart :options="chartOptions" />
<div>{{testresults}}</div>
</div>
</template>
<script>
import axios from "axios"
export default {
data() {
return {
testresults: [],
loadAPI: false,
chartOptions: {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
title: {
text: 'Visual Test results'
},
xAxis: {
categories: ['passed', 'failed', 'skipped']
},
series: [{
name: 'Results',
colorByPoint: true,
data: [{
name: 'passed',
y: this.testresults.pass,
sliced: true,
selected: true
}]
}]
}
}
},
async mounted() {
try {
const res = await axios.get(`http://localhost:3002/backend/getresults`);
this.testresults = res.data.data[0];
console.log(testresults)
} catch (error) {
console.log(error);
}
}
}
</script>
<style lang="scss" scoped>
</style>
我收到一個錯誤,它無法讀取未定義傳遞的屬性
多虧了@Lissy93,我發現我可以在 api 通話后使用finally
,我會為任何想知道這對我有用的人更新圖表選項
<template>
<div>
<highchart :options="chartOptions" />
<div>{{testresults}}</div>
</div>
</template>
<script>
import axios from "axios"
export default {
data(){
return{
testresults:[],
loadAPI:false,
chartOptions:{}
}
},
async mounted() {
try {
const res = await axios.get(`http://localhost:3002/backend/getresults`);
this.testresults=res.data.data[0];
console.log(testresults)
}catch (error){
console.log(error);
}finally{
this.chartOptions={
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
title: {
text: 'Visual Test results'
},
xAxis: {
categories: ['passed','failed','skipped']
},
series: [{
name: 'Results',
colorByPoint: true,
data: [{ name: 'passed',
y: this.testresults.pass,
sliced: true,
selected: true}]
}]
}
}
},
computed:{
}
}
</script>
<style lang="scss" scoped>
</style>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.