首页 > 解决方案 > 无法在 Vuejs 上下文中使用 chartjs 中的 API 调用显示图表

问题描述

我试图通过调用 API 使用 chartjs 显示图表,但无法这样做。

这是我的 LineChart.vue:

<script>
import {Line, mixins} from 'vue-chartjs' // We specify what type of chart we want from vue-chartjs and the mixins module
const { reactiveProp } = mixins
export default { //We are extending the base chart class as mentioned above
  extends: Line,
  mixins: [reactiveProp],
  data () {
    return {
      options: { //chart options
        lineTension: 0,
        maintainAspectRatio: false,
        legend: {
          display: false
        },
        scales: {
          yAxes: [
            {
              scaleLabel: {
                display: false
              },
              ticks: {
                beginAtZero: true,
                // eslint-disable-next-line no-unused-vars
                callback (value, index, values) {
                  return `${value  }%`
                }
              }
            }
          ],
          xAxes: [
            {
              type: 'time',
              time: {
                unit: 'month'
              },
              scaleLabel: {
                display: true,
                labelString: ''
              }
            }
          ]
        }
      }
    }
  },
  mounted () {
    // this.chartData is created in the mixin
    this.renderChart(this.chartData, this.options)
  }
}
</script>

这是我的 Home.vue,我在其中导入了 LineChart:

<template>
  <div class="chart">
    <line-chart :chart-data="datacollection"></line-chart>
  </div>
</template>

<script>
import LineChart from './LineChart'
import axios from 'axios'
import DateTime from 'luxon'
export default {
  data () {
    return {
      date: {},
      challenge: {},
      datacollection: {}
    }
  },
  component: {LineChart},
  created() {
    this.fillData()
  },
  mounted () {
    this.fillData()
  },
  methods: {
    fillData () {
      axios.get('https://my_api_goes_here')
        .then(response => {
          const results = response.data

          const dateresult = results.map(a => a.date)
          const challengeresult = results.map(a => a.challenge)

          this.date = dateresult
          this.challenge = challengeresult

          this.datacollection = {
            labels: [this.date].map(labels => DateTime.fromMillis(labels * 1000).toFormat('MMM yyyy')),
            datasets: [
              {
                data: [this.challenge],
                label: 'Africa',
                borderColor: '#7367F0'
              }
            ]
          }
        })
        .catch(error => {
          console.log(error)
        })
    }
  }
}
</script>

不知道为什么图表没有出现,即使我的其他资源已经从 API 调用中加载,当我检查我的控制台时,这是我得到的错误:

TypeError: results.map is not a function

请检查我的逻辑并告诉我错误在哪里。

标签: vue.jschart.jslinechart

解决方案


推荐阅读