javascript - 如何让组件等待 axios 从 API 获得响应?
问题描述
我正在尝试构建一个应用程序,该应用程序从我创建的 API(django-rest-framework)中提取数据,并基于该数据,它应该显示 d3 饼图。不幸的是,图表并没有等待 axios 得到响应并抛出错误。似乎图表只能访问 中定义的变量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>
我错过了什么吗?有没有办法让整个页面等到 API 调用完成并将该值推送到data()
?
解决方案
你可以通过做简单的来解决它v-if
<v-chart v-if="chartData.data" :chartData="chartData"></v-chart>
推荐阅读
- node.js - 意外的标记。需要构造函数、方法、访问器或属性。- 打字稿功能
- node.js - 为什么我的 node.js HTTP 请求失败并显示代码 501?
- c# - 如何在 C# 中将数据表传递给线程
- git - 如何在sourcesup上将两个git存储库放入一个项目中
- python - standard_init_linux.go:211: exec 用户进程在构建 tiktokapi:latest 时导致“exec 格式错误”
- json - 如何在 Postman 中随机化 ENUM 输入?
- c++ - 内存和位移运算符
- javascript - this.$refs.selectedImages.files.forEach 不是函数
- haskell - Yesod 不在范围内:类型构造函数或类表单错误
- python - 如何根据其他 2 个现有数据框创建数据框?