[Vuejs]-Populating a chartJS with data from API through axios (VueJS)

0๐Ÿ‘

I am experienced with Vue 2 and the Vue CLI (Single File Components). I did a personal project with Vue and Chart.js a couple of months ago, creating a sample bar chart and pie chart. After reading your question, I edited my project to create a sample line chart. It is working, so I am including the components here as an example.

chart-configurations.js

const sampleLineConfig = {
  type: 'line',
  data: {
    labels: [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July'
    ],
    datasets: [{
      label: 'Sample Dataset',
      data: [],
      fill: false,
      borderColor: 'rgb(75, 192, 192)',
      tension: 0.1
    }]
  },
  options: {
    responsive: false
  }
};

export {
  sampleLineConfig
}

App.vue

<template>
  <div id="app">
    <chart-test v-if="dataReady" :chartData="lineChartData" />
  </div>
</template>

<script>
  import ChartTest from '@/components/ChartTest'

  export default {
    name: 'App',
    components: {
      ChartTest
    },
    data() {
      return {
        lineChartData: [65, 59, 80, 81, 56, 55, 40],
        dataReady: false
      }
    },
    methods: {
      getData() {
        this.dataReady = true;
      }
    },
    mounted() {
      // Simulate API call
      setTimeout(this.getData(), 1000);
    }
  }
</script>

ChartTest.vue

<template>
  <div class="chart-test">
    <h3>Chart Test</h3>
    <canvas id="chart-canvas" width="500" height="500" ref="chartref"></canvas>
  </div>
</template>

<script>
  import Chart from 'chart.js';
  import { sampleLineConfig } from '@/chart-configurations.js'

  export default {
    data() {
      return {
        chartObj: null,
        chartConfig: sampleLineConfig
      }
    },
    props: {
      chartData: {
        type: Array,
        required: true
      }
    },
    methods: {
      setChartData() {
        this.chartConfig.data.datasets[0].data = this.chartData;
      }
    },
    mounted() {
      this.setChartData();
      this.chartObj = new Chart(this.$refs.chartref, this.chartConfig);
    },
    // beforeDestroy() {
    //   // This necessary if canvas is reused for a new chart
    //   this.chartObj.destroy();
    // }
  }
</script>

Leave a comment