首页 > 解决方案 > 如何让组件等待 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()?

标签: javascriptvuejs2axios

解决方案


你可以通过做简单的来解决它v-if

<v-chart v-if="chartData.data" :chartData="chartData"></v-chart>

推荐阅读