DEV Community

Cover image for Chart JS in Nuxt JS
Kamiswara Angga W.
Kamiswara Angga W.

Posted on • Edited on

Chart JS in Nuxt JS

Check out how I use Chart JS in Nuxt JS using vue-chartjs 3.5.1. By the way, I use Nuxt 2 with Vue 2 in it, and I use Tailwind CSS in my project. Make sure the Chart JS documentation that you open is version 2.9.4 because this tutorial tells you aboutu version 2.9.4.


1. Add these two dependencies to our package.json



{
  ...
  "dependencies": {
    "chart.js": "2.9.4",
    "vue-chartjs": "^3.5.1"
  }
  ...
}


Enter fullscreen mode Exit fullscreen mode

Run yarn install or npm install


2. chart.js plugin file

chart.js file

Create a new file in the plugins folder in our Nuxt project, if the plugins folder doesn't exist yet, just create it. This new file can be given any name, but we will name it chart.js.

The content of the chart.js file:



import Vue from 'vue'
import { Bar } from 'vue-chartjs'

Vue.component('BarChart', {
  extends: Bar,
  props: {
    data: {
      type: Object,
      required: true,
    },
    options: {
      type: Object,
      required: false,
      default: () => ({
        responsive: true,
        maintainAspectRatio: false,
        legend: {
          display: false,
        },
      }),
    },
  },
  watch: {
    data() {
      this.renderChart(this.data, this.options)
    },
  },
  mounted() {
    this.renderChart(this.data, this.options)
  },
})


Enter fullscreen mode Exit fullscreen mode

3. nuxt.config.js



export default {
  ...
  plugins: ['@/plugins/chart.js'],
  ...
}


Enter fullscreen mode Exit fullscreen mode

Add the chart.js plugin to the nuxt.config.js file in the plugins property.


4. Create the component



<template>
  <div class="p-2 border border-gray-500 mt-4">
    <label class="block mb-2 font-bold"> Coba Chart </label>

    <client-only>
      <BarChart :data="chartData" />
    </client-only>
  </div>
</template>

<script>
export default {
  props: {
    penilaian: {
      type: Object,
      required: true,
    },
  },
  computed: {
    chartData() {
      return {
        labels: [1, 2, 3, 4, 5],
        datasets: [
          {
            label: '',
            data: [2, 1, 16, 3, 2],
            backgroundColor: 'rgba(20, 255, 0, 0.3)',
            borderColor: 'rgba(100, 255, 0, 1)',
            borderWidth: 2,
          },
        ],
      }
    },
  },
}
</script>


Enter fullscreen mode Exit fullscreen mode

Try this example component.


5. The result

Chart JS in Nuxt JS

More or less it looks like this. This chart is called BarChart, there are also other types of charts in Chart JS. To know more and learn about the configuration, you can check the documentation:

https://www.chartjs.org/docs/2.9.4/

Top comments (0)