Search code examples
vue.jschartsvuejs2chart.jsvue-chartjs

vue-chart.js doesn't show data


This is Dijagram.vue (parent component)

<script>
  import { Line } from 'vue-chartjs'
  import config from "../config";
import axios from "axios";

  export default {
    extends: Line,
    props: {
      chartData: {
        type: Array,
        required: true,
      
      },
      chartLabels: {
        type: Array,
        required: true
      }
    },
    data () {
      return {
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: false
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      this.renderChart({
        labels: this.chartLabels,
        datasets: [
          {
            label: 'downloads',
            borderColor: '#249EBF',
            pointBackgroundColor: 'white',
            borderWidth: 1,
            pointBorderColor: '#249EBF',
            backgroundColor: 'transparent',
            data: this.chartData
          }
        ]
      }, this.options)
    },
  
  }
</script>

and this is the child component "DijagramPrikaz.vue"

<template>
  <div class="container">
    <line-chart
      v-if="loaded"
     :chartData="dani"
     :chartLabels="asset"/>
  </div>
</template>

<script>
import LineChart from './Dijagram.vue'
 import config from "../config";
import Navbar from "@/components/Navbar.vue"
import { Component, Vue } from "vue-property-decorator";
import axios from "axios";
import router from "../router";

export default {
  name: 'LineChartContainer',
  components: { LineChart },
  
  data: () => ({
    loaded: false,
           dani: [],
  asset: [],
  }),
  async mounted () {
    this.loaded = false
    try {
    axios.get(`${config.serverURL}/api/v1/dijagram`, {headers: {
      'Access-Control-Allow-Origin': '*'}})
 .then(response => {
   this.dani = response.data.map(item => item.dani)
   this.asset = response.data.map(item => item.asset.name)
 })
      this.loaded = true
    } catch (e) {
      console.error(e)
    }
  }
}
</script>

Here's the picture of how it looks like

As you can see, data is missing, and labels are default values. I have infamous "v-if=loaded", so I don't know if that's the problem or something else (though I think it's probably something in with the chart props, but I don't know since I'm new to it). Similar question have been asked, but as much as I saw, async was always the problem, which I think is not the case with me. Thanks.


Solution

  • I found the problem... it was async problem in the end. I just added "await" before axios request and it works.