Setup vue-chart.js in Nuxt.js

March 18, 2020

Install

npm install vue-chartjs chart.js --save

Edit components/BarChart.js.

import { Bar } from 'vue-chartjs'

export default {
  extends: Bar,
  props: ['data', 'options'],
  mounted () {
    this.renderChart(this.data, this.options)
  }
}

Usage: Edit pages/index.vue.

<template>
  <div class="container">
    <bar-chart :data="barChartData" :options="barChartOptions" :height="200" />
  </div>
</template>

<script>
import BarChart from '~/components/BarChart'

const chartColors = {
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(75, 192, 192)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(201, 203, 207)'
};

export default {
  data() {
    return {
      barChartData: {
        labels: ['Jan', 'Feb', 'Mar'],
        datasets: [
          {
            label: 'Income',
            // backgroundColor: ["red", "orange", "yellow"],
            backgroundColor: [chartColors.red, chartColors.orange, chartColors.yellow],
            data: [10, 15, 20]
          }
        ]
      },
      barChartOptions: {
        responsive: true,
        legend: {
          display: false,
        },
        title: {
          display: true,
          text: 'Monthly Income'
        },
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    }
  },
  components: {
    BarChart
  }
}
</script>

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.