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

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:

Continue reading %Creating Beautiful Charts Using Vue.js Wrappers for Chart.js%


Source: Sitepoint