[Chartjs]-Vuejs with ChartJS populate from API

4👍

You can use Array.map to extract necessary data.

<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar, mixins } from 'vue-chartjs'
import axios from 'axios'

export default {
  mixins: [mixins.reactiveData],
  data() {
    return {
      chartData: ''
    }
  },
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData)
  },
  created() {
    axios.get(`https://localhost:44379/api/DailyStudents`)
      .then(response => {
        // JSON responses are automatically parsed.
        const responseData = response.data
        this.chartData = {
          labels: responseData.map(item => item.day),
          datasets: [
            label: 'Daily Students',
             backgroundColor: '#f87979',
             data: responseData.map(item => item.totalStudents)
          ]
        }
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}
</script>

Note that you need to use mixins.reactiveData to make component reactive with data change.

Leave a comment