[英]How to make a componenet wait for axios to get a response from API?
I'm trying to build an app that pulls data from API created by me (django-rest-framework) and based on that data, it should display d3 pie chart.我正在尝试构建一个应用程序,从我创建的 API 中提取数据(django-rest-framework)并基于该数据,它应该显示 d3 饼图。 Unfortunatly, the chart does not wait for axios to get a response a throws an error.
不幸的是,图表不等待 axios 得到响应,然后抛出错误。 It seems that chart can get access only to variables defined in
data()
, and any later changes on that variables does't affect it.似乎图表只能访问
data()
中定义的变量,并且以后对该变量的任何更改都不会影响它。
<template v-if="loaded">
<div id="question">
<h1>Question view</h1>
<h2>{{question}}</h2>
<v-chart :chartData="chartData"></v-chart>
</div>
</template>
<script>
export default {
data() {
return {
loaded: false,
question: null,
chartData: {
chartType: 'pieChart',
selector: 'chart',
title: 'Important Data',
width: 1000,
height: 700,
metric: 'option_votes',
dim: 'option_text',
data: null,
},
}
},
created: function() {
this.axios
.get("http://localhost:8000/api/questions/" + this.$route.query.q)
.then(response => (this.question = response.data))
.then(response => (this.chartData.data = response.data.options))
.then(this.loaded = true)
.catch(error => (this.error = error));
},
};
</script>
<style lang="scss" scoped>
</style>
Am I missing something?我错过了什么吗? Is there a way for a whole page to wait until API call is done and push that value to
data()
?有没有办法让整个页面等到 API 调用完成并将该值推送到
data()
?
You can solve it by doing simple v-if
您可以通过执行简单
v-if
来解决它
<v-chart v-if="chartData.data" :chartData="chartData"></v-chart>
Ok, I've got it to work but placing all data inside one object:好的,我已经让它工作了,但是将所有数据放在一个 object 中:
<template>
<div id="question">
<h1>{{ data.question.question_text }}</h1>
<v-chart :chartData="data.chartData"></v-chart>
</div>
</template>
<script>
export default {
data() {
return {
data: null
};
},
created: function() {
this.axios
.get("http://localhost:8000/api/questions/" + this.$route.query.q)
.then(
response =>
(this.data = {
question: response.data,
chartData: {
chartType: "pieChart",
selector: "chart",
title: "Important Data",
width: 1000,
height: 700,
metric: "option_votes",
dim: "option_text",
data: response.data.options
}
})
)
.catch(error => (this.error = error));
}
};
</script>
It looks like two.then() functions referencing response object is not valid.看起来两个引用响应 object 的函数无效。
Isn't data supposed to be an object returned by a function?数据不应该是由 function 返回的 object 吗?
Like so:像这样:
data: function () {
return { a: 1 }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.