未捕获(在承诺中)TypeError:此.renderChart不是函数VueJs Chart.js

roqulrg3  于 2022-11-06  发布在  Chart.js
关注(0)|答案(1)|浏览(204)

我尝试使用Chart.js和VueJs创建一个COVID19可视化站点
这是MyApp.vue,它包含API调用并将数据存储到数组中

<template>
<div id="app" class="container">
  <div class="row mt-5" v-if="PositiveCases.length > 0">
    <div class="col">
      <h2>Positives</h2>
      <lineChart :chartData="PositiveCases" :options="chartOptions" label="Positive" />
    </div>
  </div>
</div>
</template>

<script>
import axios from "axios";
import moment from 'moment'
import lineChart from "./components/lineChart.vue";
export default {
  name: 'App',
  components: {
    lineChart
  },
  data(){
    return{
      PositiveCases : [],
      Deaths: [],
      Recoverd: [],
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false
      }
    }
  },
  async created(){
    const {data} = await axios.get('https://api.covid19api.com/live/country/egypt')
    //console.log(data);
    data.forEach(d => {
      const date = moment(d.Date,"YYYYMMDD").format("MM/DD")
      const {Confirmed,Deaths,Recovered} = d
      this.PositiveCases.push({date, total : Confirmed})
      this.Deaths.push({date, total : Deaths})
      this.Recoverd.push({date, total : Recovered})

      // console.log("PositiveCases",this.PositiveCases);
      // console.log("Deaths",this.Deaths);
      // console.log("Recoverd",this.Recoverd);
    });
  }
}
</script>

这是我的lineChart.vue,它包含折线图代码,数据正确存储在日期和总计中

<script>
import {Line} from 'vue-chartjs'
export default {
    extends: Line,
    props: {
        label:{
            type: String,
        },
        chartData:{
            type: Array,
        },
        options:{
            type: Object,
        }
    },
    mounted(){
        const dates = this.chartData.map(d => d.date).reverse()
        const totals = this.chartData.map(d => d.total).reverse()
        console.log("dates",dates);
        console.log("totals",totals);
        this.renderChart({
            labels: dates,
            datasets: [{
                label: this.label,
                data: totals,
            }],
        },this.options
    )
    }
}
</script>

控制台中的错误显示

我想知道解决方案是什么,所有数据都正确存储在两个文件中

cyvaqqii

cyvaqqii1#

您使用的是vue-chart.js的V4版本,图表创建过程已经更改,您可以在迁移指南中阅读此处。
因此,您现在必须使用实际的组件并将数据传递给它,而不是调用旧语法中的this.renderChart,如下所示:

<template>
  <Bar :chart-data="chartData" />
</template>

<script>
// DataPage.vue
import { Bar } from 'vue-chartjs'
import { Chart, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

Chart.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: { Bar },
  data() {
    return {
      chartData: {
        labels: [ 'January', 'February', 'March'],
        datasets: [
          {
            label: 'Data One',
            backgroundColor: '#f87979',
            data: [40, 20, 12]
          }
        ]
      }
    }
  }
}
</script>

相关问题