为什么 vue-chartjs 不显示我传递的数据?

问题描述

正在开发一个 covid 应用程序以熟悉 vue2js。

我现在正在尝试使用 vue-chartjs 获取图表,但未能将数据传递给图表/图表组件。

我使用 vuex 发出 API 请求并将数据传递给我的组件:CountryGraph.vue,其中包含带有图表本身的 Graph.vue。

vuex -> CountryGraph.vue -> Graph.vue

将数据传递到 CountryGraph.vue 工作:

Data from vuex into CountryGraph.vue

但是当我尝试将我的数据 (countryGraph) 作为道具传递给我的 char/Graph.vue 组件时,它没有完成,我在 Graph.vue 中只获得了值 undefined

LineChart Undefined

为什么?

在我的代码下面,首先是 CountryGraph.vue:

<template>
    <section class="countryGraph">
        <LineChart
            :chartdata="chartData"
            :options="chartOptions"
        />
    </section>
</template>

<script>
import { mapGetters,mapActions } from "vuex";
import LineChart from "../graph/Graph";

export default {
    name: "CountryGraph",components: { LineChart },data: () => ({
        chartData: {
            labels: this.countryGraph.map((el) => el.date),datasets: [
                {
                    label: "Confirmed",backgroundColor: "#f87979",data: this.countryGraph.map(
                        (el) => el.confirmed
                    ),},],chartOptions: {
            responsive: true,maintainAspectRatio: false,}),methods: {
        ...mapActions(["selectCountryGraph"]),computed: {
        ...mapGetters(["countryGraph"]),};
</script>

<style></style>

我的 chart/Graph.vue 组件是这样制作的,我可以重用它(如 vue-chartjs guide 中所述):

<script>
import { Bar } from "vue-chartjs";

export default {
    extends: Bar,props: {
        chartdata: {
            type: Object,default: null,options: {
            type: Object,mounted() {
        this.renderChart(this.chartdata,this.options);
    },};
</script>

<style />

当我使用模拟数据时,比如代替

labels: this.countryGraph.map((el) => el.data)

我愿意labels: ["q","w","e","r","t"] 而不是

data: this.countryGraph.map(el => el.confirmed)

我愿意data: [0,1,2,3,4]

一切正常。

此外,当我将变量直接传递给组件时,例如:

<LineChart
            :chartdata="this.countryGraph.map((el) => el.data)"
            :options="chartOptions"
        />

然后我可以在子(Graph.vue)组件中将数据视为道具。 但在这种情况下,我使用 v-bind: 而在较早的情况下不使用。也许这就是问题所在?

解决方法

需要注意的几个问题:

  1. 看起来您正在映射一个不存在的属性(el.data 应该是 el.date)。可能只是问题中的一个错字。

    this.countryGraph.map((el) => el.data) ❌
                                        ^
    
  2. data() 不是响应式的,不能依赖计算道具,所以 countryGraph 计算道具在 data() 中将不可用并且不会更新 chartData随着变化。解决此问题的一种方法是使 chartData 成为计算道具:

    export default {
        computed: {
            ...mapGetters(["countryGraph"]),// don't use an arrow function here,as we need access to component instance (i.e.,this.countryGraph)
            chartData() {
              return {
                  labels: this.countryGraph.map((el) => el.date),datasets: [
                      {
                          label: "Confirmed",backgroundColor: "#f87979",data: this.countryGraph.map((el) => el.confirmed),},],}
            }
        }
    }