Recently I was playing around with the Chart.js library and integrated it into one of my Vue applications. Even if there are some wrapper libraries to use Chart.js together with Vue and TypeScript, I had issues integrating them into my Vue project. In this blog post, I want to show you how to create your own Chart components in Vue by using the regular Chart.js library.
Requirements
- Vue Project
- Vue Class Components
- Vue Property Decorator
Installation
First, add the following packages to your Vue application.
$ yarn add chart.js @types/chart.js
Once these packages are installed, create a new charts folder and the corresponding Chart component inside the components directory.
$ mkdir src/components/charts
$ touch src/components/charts/Doughnut.vue
Add the following content to the Doughnut.vue file:
<template>
<canvas id="doughnut" />
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import Chart from 'chart.js'
@Component
export default class Doughnut extends Vue {
@Prop({ default: [] }) readonly labels!: Array<string>
@Prop({ default: [] }) readonly colors!: Array<string>
@Prop({ default: [] }) readonly data!: Array<number>
@Prop({
default: () => {
return Chart.defaults.doughnut
}
})
readonly options: object | undefined
mounted() {
this.createChart({
datasets: [
{
data: this.data,
backgroundColor: this.colors
}
],
labels: this.labels
})
}
createChart(chartData: object) {
const canvas = document.getElementById('doughnut') as HTMLCanvasElement
const options = {
type: 'doughnut',
data: chartData,
options: this.options
}
new Chart(canvas, options)
}
}
</script>
As you can see, we are declaring properties for the chart data and configuration. This makes our component reusable and we are able to inject the values from another component.
Now, you can import and use the created Doughnut component. In this example, the component has been added to the Home view of a new Vue project:
<template>
<div class="home">
<Doughnut
:data="[25, 75, 30]"
:labels="['Red', 'Green', 'Blue']"
:colors="['red', 'green', 'blue']"
/>
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
</div>
</template>
Finally, start the Vue development server and open your browser on the related address to see the result:
Top comments (1)
instead of using
const canvas = document.getElementById('doughnut') as HTMLCanvasElement
why not add a ref tag to the canvas and do this instead
const canvas = this.$refs.doughnut