Add “Charts & Graphs” into your Vue.js application

Any user dashboard will have some report level data. And nothing can be much more visually appealing and easy than showing some Charts and Graphs.

In this tutorial let us see how we can use a very popular chart and graph library char.js inside our vue.js application.

To use Chart.js we are going to use a vue.js wrapper library which is “vue-chartjs”. So, you need to do a quick

npm install vue-chartjs — save

This particular package will automatically pull in Chart.js as it’s dependency.

Now, once the package is pulled in, we are all set to create our first component and extend the Chart js library. I have named my component “ActivityGraph.vue” and I have kept the template HTML separate. This is how the component’s code looks

<template src="./ActivityGraph.html"></template>
<script>
import LineChat from './LineChart'
export default {
components: {
'line-chart': LineChart
}
}
</script>

Now, if you see here I am using a component called LineChart. This is the file where all the logic to render the code will go in. Let’s see the LineChart file then

import {Line} from 'vue-chartjs'
export default Line.extend({
mounted () {
this.renderChart({
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [
{label: 'My activities', backgroundColor: '#dd4b39', data: [40, 39, 31, 11, 45, 50]},
{label: 'System activities', backgroundColor: '#dddddd', data: [45, 43, 20, 55, 34, 90]},
]
}, {responsive: true, maintainAspectRatio: false})
}
})

So, although this data is hard coded right now but it will give you a sense how the graph data will go in. And this is the HTML file which is working as the template where I have just added the component tag

<div class="ActivityGraphWrapper">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Activity data</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="row">
<div class="col-md-12">
<line-chart></line-chart>
</div>
</div>
</div>
<!-- /.box-body -->
</div>
</div>

This is how a typical chart looks inside the application:

And if you want then you can watch this video series where I have gone from a basic implementation with hardcoded data to a full REST api based live graph.

Video explaining how to implement the Chart.js library inside Vue.js application
Show your support

Clapping shows how much you appreciated Amitav Roy’s story.