Using Chart.js in Vue.js

 Nowadays data visualization is gaining more importance. It is a difficult job to do data visualization in your designs. When you have to work on charts in a daily basis chart.js will be really helpful. It is simple and powerful alternative to create clear graphs with HTML5 <canvas> element. Vue’s data() object is wonderful to store our data and manipulate it to turn it to a graph. In your Vue.js application using webpack-simple template install Chart.js.

$ vue init webpack-simple <project-name>

$ cd <project-name>

$ npm install

$ npm install chart.js –save

In the App.vue file remove the generated codes. <canvas> will be in the root #app element. Import Chart.js using ES6 into Vue.component. 

import Chart from 'chart.js';

Let’s look at an example for the chart. The number of moons per planet in our solar system and the overall mass of each planet are our two datasets. We will see two different chart types to show the relations in data. The chart requires a <canvas> element in HTML code. The chart id is used as a selector to bind the JavaScript to it. 

<template>

  <div id="app">

    <canvas id="planet-chart"></canvas>

  </div>

</template>

Each chart will have the following basic structure.

const ctx = document.getElementById('planet-chart');

const myChart = new Chart(ctx, {

  type: '',

  data: [],

  options: {},

});

By adding the data to this chart object you can start creating the graph. Creating a function in your component method object with two parameters charted and chartData this process will be easier.

methods: {

  createChart(chartId, chartData) {

    const ctx = document.getElementById(chartId);

    const myChart = new Chart(ctx, {

      type: chartData.type,

      data: chartData.data,

      options: chartData.options,

    });

  }

}

For creating the chart’s data create a new .js file say chart-data.js  in the root src folder.  Create a const and name it for our example we call it planetChartData.

export const planetChartData = {

  type: 'line',

  data: {

    labels: ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'],

    datasets: [

      { // one line graph

        label: 'Number of Moons',

        data: [0, 0, 1, 2, 67, 62, 27, 14],

        backgroundColor: [

          'rgba(54,73,93,.5)', // Blue

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)',

          'rgba(54,73,93,.5)'

        ],

        borderColor: [

          '#36495d',

          '#36495d',

          '#36495d',

          '#36495d',

          '#36495d',

          '#36495d',

          '#36495d',

          '#36495d',

        ],

        borderWidth: 3

      },

      { // another line graph

        label: 'Planet Mass (x1,000 km)',

        data: [4.8, 12.1, 12.7, 6.7, 139.8, 116.4, 50.7, 49.2],

        backgroundColor: [

          'rgba(71, 183,132,.5)', // Green

        ],

        borderColor: [

          '#47b784',

        ],

        borderWidth: 3

      }

    ]

  },

  options: {

    responsive: true,

    lineTension: 1,

    scales: {

      yAxes: [{

        ticks: {

          beginAtZero: true,

          padding: 25,

        }

      }]

    }

  }

}


export default planetChartData;

To manipulate this data in future we are exporting the planetChartData and importing it into another JavaScript file. Here we are importing the data into App.vue component.

import planetChartData from './chart-data.js';

We are storing chart’s data into Vue’s data() function as shown below.

data() {

  return {

    planetChartData: planetChartData,

  }

}

Now we are initializing the chart and writing it to <canvas> element in the template. To initialize run createChart() function in the component’s mounted() lifecycle method.

mounted() {

  this.createChart('planet-chart', this.planetChartData);

}

Now the function calls the chart and component is mounted.