JavaScript
Article
By Yomi Eluwande

Creating Beautiful Charts Using Vue.js Wrappers for Chart.js

By Yomi Eluwande

A maid positioning objects representing different types of chart

Charts are an important part of modern websites and applications. They help to present information that cannot be simply represented in text. Charts also help to make sense of data that would ordinarily not make sense in a textual format by presenting them in a view that’s easy to read and understand.

In this article I will show you how to represent data in the form of various types of chart with the help of Chart.js and Vue.js.
Chart.js is a simple yet flexible JavaScript charting library for developers and designers that allows drawing of different kinds of chart by using the HTML5 canvas element. A good refresher on Chart.js can be read here.

Vue.js is a progressive JavaScript framework, which we’ll use alongside Chart.js to demonstrate the chart examples. There’s an awesome primer on using Vue.js on Sitepoint and that can be read here. We’ll also be using vue-cli to scaffold a Vue.js project for the demo we are going to build. vue-cli is a simple CLI for scaffolding Vue.js projects. It offers various templates from which an app can be built, but we will be using the webpack template to bootstrap our app.

Charts, Charts, Charts

There are different types of JavaScript charting libraries and various chart wrappers built on Vue.js, but as we are focused on Chart.js in this article, we will be looking at Vue wrappers for Chart.js.

There is an awesome collection of Vue wrappers for charts on the awesome-vue repo on GitHub but we are only interested in the following Chart.js wrappers:

We will be using the various wrappers to demonstrate how to create different types of chart and also touch on the unique features that each of these wrappers possesses.

Scaffolding the Project with vue-cli

Let’s get started by installing vue-cli with the following command:

npm install -g vue-cli

Once that’s done, we can then get started with scaffolding a project by typing in:

vue init webpack my-project

We are specifying that we want a Vue.js app created for us with the webpack template and the name of the project as my-project. Respond to all of the questions and let vue-cli do the rest of the magic. Awesome!

Now let us go ahead to install the dependencies and Chart.js wrappers needed for our app:

npm install chart.js chartkick hchs-vue-charts vue-chartjs vue-chartkick

Tip: If you use npm 5, no need for the --save flag anymore as all packages are automatically saved now. Read more about that here.

This will install all the dependencies and Chart.js Vue wrappers needed. Let’s test what we have so far and run our application and see if the app was successfully created. According to the vue-cli docs, running npm run dev will create a first-in-class development experience in which we can interact and engage with our app. So let’s do that.

npm run dev

You can visit localhost:8080 in your browser to see the welcome page.

Adding Routes

Next thing we want to do is create the different routes in which we can view the charts for each of the wrappers above. At the end, we would like to have a /charts route to display charts made with the vue-charts wrapper, /chartjs to display charts made with the vue-chartjs wrapper, and lastly /chartkick to display charts made with the vue-chartkick wrapper.

Navigate to the router folder of the app and open up theindex.js file. Let’s replace the content of that file with this:

import Vue from 'vue' // Import Vue from node_modules
import Router from 'vue-router' // Import Vue Router from node_modules
import Home from '@/components/Home' //The Home component that's in charge of everything we see on the app's homepage
import VueChartJS from '@/components/VueChartJS' //The VueChartJS component that displays the vue-chartjs charts.
import VueChartKick from '@/components/VueChartKick' //The VueChartJS component that displays the vue-chartkick charts.
import VueCharts from '@/components/VueCharts' //The VueChartJS component that displays the vue-charts charts.

//Specify that we want to use Vue Router
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/chartjs',
      name: 'VueChartJS',
      component: VueChartJS
    },
    {
      path: '/chartkick',
      name: 'VueChartKick',
      component: VueChartKick
    },
    {
      path: '/charts',
      name: 'VueCharts',
      component: VueCharts
    }
  ]
})

Before we discuss the code above, make sure to create the files below in the src/components/ folder. This is done so that the routes defined above have their own component.

  • VueChartJS.vue
  • VueChartKick.vue
  • VueCharts.vue

So what’s happening in the code block above?

We imported some files which are the Vue components that we created above. Components are one of the most powerful features of Vue. They help us extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to.

Lastly, we defined the routes and components which will serve the different pages we need to display the different charts.

Home Component

As mentioned above, the Home component serves as the default (/) route and we will need to create it. We can do that, or simply rename the existing Hello.vue file to Home.vue and replace the content with the code block below.

<template>
  <section class="hero is-success is-fullheight">
    <div class="hero-body">
      <div class="container">
        <h1>Creating Beautiful Charts Using Vue.js Wrappers For Chart.js</h1>
        <ul>
          <li><router-link to="/chartjs">vue-chartjs</router-link></li>
          <li><router-link to="/charts">vue-charts</router-link></li>
          <li><router-link to="/chartkick">vue-chartkick</router-link></li>
        </ul>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'home'
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .home {
    display: flex;
    align-items: center;
    align-content: center;
    justify-content: center;
  }
  h1, h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
    text-decoration: underline;
  }
</style>

Adding Bulma

One more thing before we start adding charts. Let’s add the Bulma CSS framework to the app. This should make things easier when it comes to CSS.

Open the index.html in the root of the app directory and add the following inside the head tag:

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.2/css/bulma.min.css" rel="stylesheet">

We can now move on to creating charts!

Making Charts with vue-chartjs

vue-chartjs is a Chart.js wrapper that allows us to easily create reuseable chart components. Reusability means we can import the base chart class and extend it to create custom components.

With that being said, we will be demonstrating 4 types of charts that can be built using vue-chartjs: A Line Chart, Bar Chart, Bubble Chart, and a Bar Chart that demonstrates Reactivity (the chart updates whenever there’s a change in the dataset).

So before we go ahead, make sure these files are created inside the src/components/ folder.

  • LineChart.vue
  • BarChart.vue
  • BubbleChart.vue
  • Reactive.vue

Line Chart

To create a Line chart, we will create a component to render this type of chart only. Open the LineChart.vue component file inside the src/components folder and type in the following code:

<script>
  //Importing Line class from the vue-chartjs wrapper
  import {Line} from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default Line.extend({ 
    data () {
      return {
        datacollection: {
        //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], 
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
    //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  })
</script>

Let’s discuss what the code above is doing. The first thing we did was import the chart class we needed (in this case, Line) from the vue-chartjs and exported it.

The data property contains a datacollection object which contains all the information we’ll need to build the Line chart. This includes the Chart.js configuration, like labels, which will be represented on the x-axis, the datasets, which will be represented on the y-axis, and the options object, which controls the appearance of the chart.

The mounted function calls renderChart() which renders the chart with the datacollection and options objects passed in as parameters.

Now, let’s open the VueChartJS.vue file and type in the following code:

<template>
  <section class="container">
    <ul>
      <li><router-link to="/">Home</router-link></li>
      <li><router-link to="/chartjs">vue-chartjs</router-link></li>
      <li><router-link to="/charts">vue-charts</router-link></li>
      <li><router-link to="/chartkick">vue-chartkick</router-link></li>
    </ul>
    <h1>Demo examples of vue-chartjs</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <line-chart></line-chart>
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Bubble Chart</h3>
        <!--Bubble Chart example-->
      </div>
      <div class="column">
        <h3>Reactivity - Live update upon change in datasets</h3>
        <!--Reactivity Line Chart example-->
      </div>
    </div>
  </section>
</template>

<script>
  import LineChart from '@/components/LineChart'
  import BarChart from '@/components/BarChart'
  import BubbleChart from '@/components/BubbleChart'
  import Reactive from '@/components/Reactive'

  export default {
    name: 'VueChartJS',
    components: {
      LineChart,
      BarChart,
      BubbleChart,
      Reactive
    }
  }
</script>

<style scoped>
  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
</style>

The VueChartJS.vue file contains the template section which holds the HTML code, a script section which holds the JavaScript code and a style section which holds the CSS code.

Inside the template section, we wrote code to display a menu that shows links to the other pages in the application. After that, we used columns class from Bulma to create a layout that has two columns and two rows. We also added a line-chart component which will be created in the script section

Inside the script section, we imported the .vue files we created earlier and referenced them in the components object. This means we can then use them in the HTML code like this line-chart, bar-chart, bubble-chart and reactive.

Now if you run npm run dev and navigate to /chartjs. The Line Chart should display on that page.

See the Pen vue-chart.js – line chart by SitePoint (@SitePoint) on CodePen.

Bar Chart

For the next chart, we will create a custom component that helps to render Bar Charts only. Open the BarChart.vue component file inside the src/components folder and type in the following code:

<script>
  //Importing Bar class from the vue-chartjs wrapper
  import {Bar} from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default Bar.extend({
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [40, 20, 30, 50, 90, 10, 20, 40, 50, 70, 90, 100]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
    //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  })
</script>

The code above works similarly to the one in the LineChart.vue file. The only difference here is that the Bar class is imported and extended instead of Line.

One more thing, before we can see our Bar Chart, we need to edit the VueChartJS.vue file and replace <!--Bar Chart example--> with <bar-chart></bar-chart>. We are simply using the Bar component we created inside in our HTML template.

See the Pen vuechart-js – bar chart by SitePoint (@SitePoint) on CodePen.

Bubble Chart

For the Bubble chart, we will create a component that helps to render Bar Charts only.

Note: bubble charts use bubbles/circles to display data in a three dimension method (x, y, r). x is used to display the horizontal axis data, y is used to display the vertical data and r is used to display the size of the individual bubbles.

Open the BubbleChart.vue component file inside the src/components folder and type in the following code:

<script>
  //Importing Bubble class from the vue-chartjs wrapper
  import {Bubble} from 'vue-chartjs'
  //Exporting this so it can be used in other components
  export default Bubble.extend({
    data () {
      return {
        datacollection: {
          //Data to be represented on x-axis
          labels: ['Data'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              pointBackgroundColor: 'white',
              borderWidth: 1,
              pointBorderColor: '#249EBF',
              //Data to be represented on y-axis
              data: [
                {
                  x: 100,
                  y: 0,
                  r: 10
                },
                {
                  x: 60,
                  y: 30,
                  r: 20
                },
                {
                  x: 40,
                  y: 60,
                  r: 25
                },
                {
                  x: 80,
                  y: 80,
                  r: 50
                },
                {
                  x: 20,
                  y: 30,
                  r: 25
                },
                {
                  x: 0,
                  y: 100,
                  r: 5
                }
              ]
            }
          ]
        },
        //Chart.js options that controls the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
    //renderChart function renders the chart with the datacollection and options object.
      this.renderChart(this.datacollection, this.options)
    }
  })
</script>

The code above works similarly to the one in the LineChart.vue and BarChart.vue file. The difference here is that the Bubble class is imported and extended instead of Line or Bar and the datasets object takes in different values for x, y and z.

One more thing before we can see our Bubble Chart, we need to do the same thing we did for other charts edit the VueChartJS.vue file and replace <!--Bubble Chart example--> with <bubble-chart></bubble-chart>.

See the Pen vue-chartjs – bubble chart by SitePoint (@SitePoint) on CodePen.

Bar Chart that demonstrates Reactivity

The last example we will be demonstrating with vue-chartjs is how it can be used to make a chart that automatically updates whenever there is a change in the dataset. It’s important to note that Chart.js ordinarily does not offer this feature but vue-chartjs does with the help of any of the two mixins.

  • reactiveProp
  • reactiveData

Open the Reactive.vue component file inside the src/components folder and type in the following code:

<script>
  //Importing Bar and mixins class from the vue-chartjs wrapper
  import {Bar, mixins} from 'vue-chartjs'
  //Getting the reactiveProp mixin from the mixins module.
  const { reactiveProp } = mixins
  export default Bar.extend({
    mixins: [reactiveProp],
    data () {
      return {
        //Chart.js options that control the appearance of the chart
        options: {
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              },
              gridLines: {
                display: true
              }
            }],
            xAxes: [ {
              gridLines: {
                display: false
              }
            }]
          },
          legend: {
            display: true
          },
          responsive: true,
          maintainAspectRatio: false
        }
      }
    },
    mounted () {
      // this.chartData is created in the mixin and contains all the data needed to build the chart.
      this.renderChart(this.chartData, this.options)
    }
  })
</script>

The first thing we did in the code above was to import the Bar and mixins class from the vue-chartjs wrapper and extend Bar. We also extracted the reactiveProp mixin from the mixins module to be used for reactivity.

reactiveProp extends the logic of your chart component and automatically creates a prop named chartData and adds a Vue watcher on this prop. We did not create a dataset object this time around as all the data needed will be inside the chartData prop.

For this to work, we’ll need to edit our VueChartJS.vue even further. Open VueChartJS.vue and after the components method, edit with the following code:

    data () {
      return {
        // instantiating datacollection with null
        datacollection: null
      }
    },
    created () { 
    //anytime the vue instance is created, call the fillData() function.
      this.fillData()
    },
    methods: {
      fillData () {
        this.datacollection = {
          // Data for the y-axis of the chart
          labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              // Data for the x-axis of the chart
              data: [this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt(), this.getRandomInt()]
            }
          ]
        }
      },
      getRandomInt () { 
        // JS function to generate numbers to be used for the chart
        return Math.floor(Math.random() * (50 - 5 + 1)) + 5
      }
    }

Let’s go through the code above. In the data object we return datacollection which is set to null and in the created method, we call fillData() anytime the component instance is created. The fillData function will be created in the methods object.

In the methods object, we create a function called fillData. This function creates a datacollection object which contains a label array (data for the x-axis), a datasets array which holds the data array needed for the y-axis.

Note: the content of the data array is a getRandomInt function which generates a random number for us.

Finally, to display our chart and see if reactivity works, replace <!--Reactivity Line Chart example--> with:

<reactive :chart-data="datacollection"></reactive>
<button class="button is-primary" @click="fillData()">Randomize</button>

We are using the reactive component we created and passing the content of datacollection to the chart-data props to display the chart. And we also have a button that calls the fillData() method anytime its clicked on.

Navigate to /chartjs route in the app to see the new chart and click on the Randomize button to see the Chart automatically render again with the new data in realtime.

See the Pen vue-chartjs – reactive bar chart by SitePoint (@SitePoint) on CodePen.

--ADVERTISEMENT--

Making Charts With vue-charts

vue-charts takes a very different approach to building charts from vue-chartjs. It doesn’t require you to create separate components to process data and render chart, all data required for the chart can be instantiated in the Vue instance like this:

    data () {
      return {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        dataset: [65, 59, 80, 81, 56, 55, 40]
      }
    }

And we can easily display a line chart by using <chartjs-line></chartjs-line> in our template, a bar chart by using <chartjs-bar></chartjs-bar>, and a radar chart by using <chartjs-radar></chartjs-radar>.

Before we go on, we need to register vue-charts globally. Open the main.js inside the src folder and add the following lines of code under the existing import statements.

import 'chart.js'
import 'hchs-vue-charts'

Vue.use(window.VueCharts)

We simply just imported the Chart.js library and hchs-vue-charts wrapper from node_modules and registered it globally with Vue.use(window.VueCharts).

Now let’s get started on this so we can fully demonstrate the usage of vue-charts. Open up the VueCharts.vue file we created earlier and type in the following code.

<template>
  <section class="container">
    <ul>
      <li><router-link to="/">Home</router-link></li>
      <li><router-link to="/chartjs">vue-chartjs</router-link></li>
      <li><router-link to="/charts">vue-charts</router-link></li>
      <li><router-link to="/chartkick">vue-chartkick</router-link></li>
    </ul>
    <h1>Demo examples of vue-charts</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart Example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart Example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Radar Chart</h3>
        <!--Radar Chart Example-->
      </div>
      <div class="column">
        <h3>Data Binding Line Chart</h3>
        <!--Data Binding Line Chart Example-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueCharts',
    data () {
      return {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        dataset: [65, 59, 80, 81, 56, 55, 40]
      }
    }
  }
</script>

<style scoped>
  ul {
    list-style-type: none;
    padding: 0;
  }
  li {
    display: inline-block;
    margin: 0 10px;
  }
  a {
    color: #42b983;
  }
</style>

In the code block above, we created a menu that shows the links to other pages in the application. We also created placeholders for charts and all we have to do is start putting them in.
We then added the labels and data we’ll be using for the various charts in the data object inside the script section and some CSS inside the style section.

Let’s begin to create the charts now.

Line Chart

To add the Line Chart, all we have to is add this <chartjs-line></chartjs-line> in place of the comment Line Chart Example in the template section of the VueCharts.vue file. We don’t need to import any component because vue-charts has been declared globally in main.js.

Bar Chart

We do the same here. Add this <chartjs-bar></chartjs-bar> in place of the comment Bar Chart example in the template section of the VueCharts.vue file.

Radar Chart

We do the same here. Add this <chartjs-radar></chartjs-radar> in place of the comment Radar Chart example in the template section of the VueCharts.vue file.

Once that’s done, you can navigate to /charts and check out the charts we just created.

See the Pen vue-charts demo by SitePoint (@SitePoint) on CodePen.

Data Binding example with Line Chart

Data binding in vue-charts is almost similar to that of vue-chartjs. vue-charts automatically updates the chart whenever the dataset changes.

To test this, we’ll create a function named addData and add it to the methods object of the component:

    methods: {
      addData () {
        this.dataset.push(this.dataentry)
        this.labels.push(this.datalabel)
        this.datalabel = ''
        this.dataentry = ''
      }
    }

The addData method pushes the current value of the data form input and label form input (which we’ll be adding soon) to the current dataset. Now let’s add the component as well as the form to add new data and label. Add the following piece of code in place of the comment<!--Data Binding Line Chart Example-->

    <form @submit.prevent="addData">
      <input placeholder="Add a Data" v-model="dataentry">
      <input placeholder="Add a Label" v-model="datalabel">
      <button type="submit">Submit</button>
    </form>
    <chartjs-line :labels="labels" :data="dataset" :bind="true"></chartjs-line>

The code above is a form that allows you to type in values of data and label and then submit the form. The chart will render automatically with the latest entry.

See the Pen vue-charts data binding by SitePoint (@SitePoint) on CodePen.

Making Charts with vue-chartkick

vue-chartkick is a Vue wrapper that allows you to create beautiful charts with one line. We’ll be demonstrating the use of this library with four examples. We’ll be creating a Line Chart, Bar Chart, Scatter Chart and also use the download feature (downloadable charts).

In terms of handling data needed for the chart dataset, vue-chartkick gives us two options. We can do something like <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart> in which the data is added inline or <line-chart :data="chartData"></line-chart> and we declare the chartData array in the Vue data object like this:,

data () {
  return {
    chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
  }
}

Let’s get started with using vue-chartkick. Before we go on, open the main.js file inside the src folder and add the following code:

import Chartkick from 'chartkick'
import VueChartkick from 'vue-chartkick'

Vue.use(VueChartkick, { Chartkick })

We simply just imported the Chartkick library and the vue-chartkick wrapper from node_modules and registered it globally with Vue.use(VueChartkick, { Chartkick }).

To start creating charts with vue-chartkick, open up the VueChartKick.vue file we created earlier and type in the following code.

<template>
  <section class="container">
    <ul>
      <li><router-link to="/">Home</router-link></li>
      <li><router-link to="/chartjs">vue-chartjs</router-link></li>
      <li><router-link to="/charts">vue-charts</router-link></li>
      <li><router-link to="/chartkick">vue-chartkick</router-link></li>
    </ul>
    <h1>Demo examples of vue-chartkick</h1>
    <div class="columns">
      <div class="column">
        <h3>Line Chart</h3>
        <!--Line Chart example-->
      </div>
      <div class="column">
        <h3>Bar Chart</h3>
        <!--Bar Chart example-->
      </div>
    </div>
    <div class="columns">
      <div class="column">
        <h3>Scatter Chart</h3>
        <!--Scatter chart example-->
      </div>
      <div class="column">
        <h3>Downloadable Line Chart</h3>
        <!--Downloadable line chart-->
      </div>
    </div>
  </section>
</template>

<script>
  export default {
    name: 'VueChartKick',
    data () {
      return {
        chartData: [['Jan', 44], ['Feb', 27], ['Mar', 60], ['Apr', 55], ['May', 37], ['Jun', 40], ['Jul', 69], ['Aug', 33], ['Sept', 76], ['Oct', 90], ['Nov', 34], ['Dec', 22]]
      }
    }
  }
</script>

<style scoped>
  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }
</style>

In the code block above, we again display a menu that shows the links to other pages in the application. We also created placeholders for the different types of charts we’ll be creating and all we have to do is start putting them in.

We then created the chartData array that holds data we’ll be using for the various charts in the data object inside the script section and some CSS inside the style section. Let’s begin to create the charts now.

Line Chart

Creating a Line chart with vue-chartkick is very simple and straightforward. All you have to do is bring in the vue-chartkick Line chart component and also determine what dataset you want to use, something like this <line-chart :data="chartData"></line-chart>. In this case, the data prop is set to the chartData array in the Vue data object.

Therefore, replace the comment <!--Line Chart example--> inside the VueChartKick.vue file with <line-chart :data="chartData"></line-chart> and the Line Chart should display nicely now.

Bar Chart

We can create a Bar chart just like the way we created the Line chart above. But in this case, we’ll try something different. Instead of using the chartData array as the dataset, we will add the dataset inside the props, like this <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart>.

Replace the comment <!--Bar Chart example--> inside the VueChartKick.vue file with <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart> and your Bar chart should display now.

Scatter Chart

Scatter chart also works like the Line and Bar chart above. Replace the comment <!--Scatter Chart example--> inside the VueChartKick.vue file with <scatter-chart :data="[[174.0, 80.0], [176.5, 82.3], [180.3, 73.6]]"></scatter-chart> and your Scatter chart should display now.

Downloading a Chart

vue-chartkick has a pretty neat feature that vue-chartjs and vue-charts lacks and that is the ability create downloadable charts. Once a chart has been set to downloadable, users can easily save the chart as an image. So how does this work? Let’s check it out with a Line chart

<line-chart :data="chartData" :download="true"></line-chart>

We set the :download prop to true and that means the chart is downloadable. That’s all!

Replace the comment <!--Downloadable line chart--> inside the VueChartKick.vue file with <line-chart :data="chartData" :download="true"></line-chart> to see and test the download feature on your app. You can hover over the new chart to see the download button.

Demo

See the Pen vue-chartkick demos by SitePoint (@SitePoint) on CodePen.

Comparisons

So now that we have gone through the three Vue.js wrappers for Chart.js, what are the pros and cons of each?

vue-chartjs

vue-chartjs is perhaps the most powerful of the three wrappers. It gives so much room for flexibility and also ships with a reactivity feature (ability to re-render a chart automatically if there’s been a change in the data).

A con for the wrapper would be the fact that configuring the chart can be somewhat complex at the the beginning due to the various options available and also having to create an external file to hold the configuration for the wrapper.

vue-charts

vue-chartjs is a pretty good Chart.js wrapper. It’s very easy to set up, unlike vue-chartjs. It does not require you to create separate components to process data and render chart, all data required for the chart can be instantiated in the Vue instance as seen above in the examples. It also ships with a reactivity feature (ability to render a chart automatically if there’s been a change in the dataset) without a need for mixins.

vue-chartkick

vue-chartkick is also a pretty good Chart.js wrapper. It may be the wrapper with the easiest path to usage among the three Chart.js wrapper.

The dataset for the chart can be added in two different ways in vue-chartkick. We can do something like <bar-chart :data="[['Work', 1322], ['Play', 1492]]"></bar-chart> in which the data is added inline or <line-chart :data="chartData"></line-chart> and we declare the chartData array in the Vue data object as seen above in the examples. It also ships with an awesome feature that allows you to download your charts as an image; something that the other wrappers lack.

The only disadvantage that vue-chartkick has would be the fact that it doesn’t support reactivity out of the box.

Conclusion

In this article, I introduced various Vue wrappers for Chart.js and also demonstrated examples on how to use each of them to create beautiful charts for your next web project.

The source code for this tutorial is on GitHub and you can reference it here and if you’d like to see a live demo of the tutorial, you can also see that here.

More:
Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account