Tutorial

How To Use Chart.js with Vue.js

Updated on March 12, 2021

Developer and Author

How To Use Chart.js with Vue.js

Introduction

Chart.js is a powerful way to create clean graphs with the HTML5 <canvas> element. With Vue’s data() object, it is possible to store data and manipulate it to change graphs when needed.

In this article, you will use Chart.js in a sample Vue project to display information about planets in the solar system.

Prerequisites

To complete this tutorial, you will need:

This tutorial was verified with Node v15.11.0, npm v7.6.1, vue v2.6.11, and Chart.js v2.9.4.

Step 1 — Setting Up the Project

To quickly set up the project, this article will recommend using @vue/cli.

Note: This article will take the approach of using npx to avoid a global installation of @vue/cli;

  1. npx @vue/cli create vue-chartjs-example --default

Navigate to the newly created project directory;

  1. cd vue-async-computed-example

Chart.js can be installed through npm with the following command:

  1. npm install chart.js@2.9.4

At this point, you will have a new Vue project that supports Chart.js.

Step 2 — Creating the Chart Component

This chart will consist of two datasets:

  1. The number of moons each planet in the solar system has.
  2. The mass of each planet in the solar system.

With these two datasets, we can have different chart types to show correlations in data.

Open your code editor and under src directory and components subdirectory, create a new PlanetChart.vue file.

Every Chart.js chart needs to have a <canvas> in the HTML markup. The id of the chart is used as a selector to bind the JavaScript to it.

PlanetChart.vue
<template>
  <div>
    <canvas id="planet-chart"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js'

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

Next, you will modify the App.vue file to use the new PlanetChart:

src/App.vue
<template>
  <div id="app">
    <PlanetChart/>
  </div>
</template>

<script>
import PlanetChart from './components/PlanetChart.vue'

export default {
  name: 'App',
  components: {
    PlanetChart
  }
}
</script>

Save the changes to your file.

In order to keep the component and the configuration separate, you will next be creating a new file for the chart data.

Step 3 — Creating the Chart Data

Creating a chart with Chart.js resembles the following:

const ctx = document.getElementById('example');
const exampleChart = new Chart(ctx, {
  type: '',
  data: [],
  options: {},
});

A <canvas> element is passed in along with a type, data, and options.

You will be creating a new file that defines these values. Open your code editor and under src directory, create a new planet-data.js file. Keep in mind, you will want to give it a unique and descriptive name based on the data. You can have several data objects in this file for different charts.

Add the following lines of code to planet-data.js:

src/planet-data.js
export const planetChartData = {
  type: "line",
  data: {
    labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
    datasets: [
      {
        label: "Number of Moons",
        data: [0, 0, 1, 2, 79, 82, 27, 14],
        backgroundColor: "rgba(54,73,93,.5)",
        borderColor: "#36495d",
        borderWidth: 3
      },
      {
        label: "Planetary Mass (relative to the Sun x 10^-6)",
        data: [0.166, 2.081, 3.003, 0.323, 954.792, 285.886, 43.662, 51.514],
        backgroundColor: "rgba(71, 183,132,.5)",
        borderColor: "#47b784",
        borderWidth: 3
      }
    ]
  },
  options: {
    responsive: true,
    lineTension: 1,
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true,
            padding: 25
          }
        }
      ]
    }
  }
};

export default planetChartData;

The type will be set to line. The data will consist of of two datasets, backgroundColor, borderColor, and borderWidth. The options will consist of responsive, lineTension, and scales.

Note: You can reference the Chart.js documentation for more information about line charts, as well as others like bar, polarArea, radar, pie, and doughnut.

By exporting planetChartData, you are allowing that const to be imported into another JavaScript file. More importantly, you are separating the data from the component. This best practice allows you to apply changes to only the relevant file and offers greater maintenance over time.

Revisit the PlanetChart component and add planetChartData:

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

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

Next, store the chart data in the data() function.

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

export default {
  name: 'PlanetChart',
  data() {
    return {
      planetChartData: planetChartData
    }
  }
}
</script>

Note: You can also use ES6 shorthand. Since the data property and value have the same name, you can just use planetChartData instead of planetChartData: planetChartData.

At this point, Chart.js should be installed and the chart’s data should be imported into the PlanetChart component.

You should already have a <canvas> element created in the component’s template. At this point, it’s time to initialize the chart and write to the <canvas>.

Revisit the PlanetChart component and add the create the chart in the mounted() lifecycle method:

src/components/PlanetChart.vue
<script>
import Chart from 'chart.js'
import planetChartData from '../planet-data.js'

export default {
  name: 'PlanetChart',
  data() {
    return {
      planetChartData: planetChartData
    }
  },
  mounted() {
    const ctx = document.getElementById('planet-chart');
    new Chart(ctx, this.planetChartData);
  }
}
</script>

Save the changes to your file.

Now, you can run your application with your terminal:

  1. npm run serve

Open the application in your web browser:

Screenshot of line charts of the number of moons and planetary mass.

There will be two line charts. One chart displays the number of moons for each planet. THe other chart displays the mass of each planet. The backgroundColor, borderColor, and borderWidth values have affected the appearance of the charts. Interacting with the points on the line will display the labels.

Step 4 — Displaying Mixed Charts

Chart.js also supports mixed charts. In this section, you will change the configuration of the charts from line charts to a mix of a line chart for the moon dataset and a bar chart for the mass dataset.

Revisit planet-data.js with your code editor. Modify the type property of your chart’s data and change it to bar.

src/planet-data.js
export const planetChartData = {
  type: "bar",
  data: { ... },
  options: { ... }
};

export default planetChartData;

At this point, both charts will be bar graphs.

However, you want to display a mix of bar and line graphs. To change this, in each dataset object, add a type property under the label property. For the first dataset object, give it a type property with a value of line and for the second, give it a type property with a value of bar:

src/planet-data.js
export const planetChartData = {
  type: "bar",
  data: {
    labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
    datasets: [
      {
        label: "Number of Moons",
        type: "line',
        data: [0, 0, 1, 2, 79, 82, 27, 14],
        backgroundColor: "rgba(54,73,93,.5)",
        borderColor: "#36495d",
        borderWidth: 3
      },
      {
        label: "Planetary Mass (relative to the Sun x 10^-6)",
        type: "bar",
        data: [0.166, 2.081, 3.003, 0.323, 954.792, 285.886, 43.662, 51.514],
        backgroundColor: "rgba(71, 183,132,.5)",
        borderColor: "#47b784",
        borderWidth: 3
      }
    ]
  },
  options: { ... }
};

export default planetChartData;

Save the changes to your file.

Now, you can run your application with your terminal:

  1. npm run serve

Open the application in your web browser:

Screenshot of line chart of moons and bar chart of planetary mass.

The number of moons for each planet displays as a line chart. The mass of each planet displays as a bar chart.

Conclusion

In this article, you used Chart.js in a sample Vue project to display information about planets in the solar system.

Chart.js can be used for other data visualizations. Explore the samples for inspiration in how it can be incorporated into your projects.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar

Developer and Author

I’m a software engineer from Cincinnati. I work on TypeScript apps with Vue.js. Currently a Senior Front-End Engineer at Enodo, based in Chicago.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Great walkthrough. Helped me a lot. Just 2 remarks:

  • the path in step 2 refers to a different project.
  • this whole thing works with the latest chartjs. Just add ‘/auto’ to the import: import Chart from ‘chart.js/auto’

First off, thank you for a well written guide!

I’ve been struggling with a variety of errors for days trying to use either v-charts and vue-echarts with echarts, but today I decided to just try Chart.js. This guide was the clearest and to-the-point of many, but I’m currently stuck after following the steps…

npm packages: ├── @vue/cli@4.5.12 ├── @vue/composition-api@1.0.0-rc.6 ├── chart.js@3.0.2 ├── echarts@5.0.2 ├── vue-chartjs@3.5.1 ├── vue-echarts@6.0.0-rc.4 └── vue@2.6.12

Copy pasting your code, I get the error:

"Error in mounted hook: “TypeError: chart_js__WEBPACK_IMPORTED_MODULE_0__.default is not a constructor”

found in

—> <PlanetChart> at src/components/PlanetChart.vue <App> at src/App.vue <Root>"

Do you have any idea what could’ve gone wrong? :S

Awesome! Thanks a lot. This works with vue3! Tried vue-chartjs package and it does not support vue3. So this saved me.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.