How to create a colorful doughnut in Vuejs


In this post you will learn

  • Create a TS component
  • Create props
  • Mixin multiple props and function
  • vue-chartjs
  • chartjs doughnut chart

Vue-Chartjs

Vue-chartjs is chartjs wrapper for Vue. It is JavaScript library you can use either CDN or NPM version. I going to use it with NPM, it is so easy.

npm install: npm install vue-chartjs chart.js --save

Create a doughnut

We can simply create a new component using TS /JS in your Vuejs app. Remember the component can’t have template section, since Vue don’t merge templates.

Following is a simple component which uses Mixin to combine props, Doughnut chart from vue-chartjs. The props also have default values, so that can leave the props blank for testing ( for example color).

import { Component, Mixins } from "vue-property-decorator"
import { Doughnut, mixins } from "vue-chartjs";
import Vue from "vue";

const chartProps = Vue.extend({
    props: {
        blockColors: {
            type: [],
            default: [
                "#ff6384",
                "#36a2eb",
                "#cc65fe"
            ]
        },
        data: {
            type: [] ,
            default: [140,50,60]

        },
        labels: {
            type: [],
            default: ["Red",  "Blue","Violet"],
        }
    }

});
@Component({
    extends: Doughnut, // this is important to add the functionality to your component
    mixins: [mixins.reactiveProp]
})
export default class ChjsDoughnutChart extends Mixins(mixins.reactiveProp, Doughnut,chartProps) {
    mounted() {
        // Overwriting base render method with actual data.
        this.renderChart({
            datasets: [
                {
                    backgroundColor: this.blockColors,
                    data: this.data,                    
                }
            ],
            labels: this.labels
        })
    }
}

Use the component

We can import and use the component in the template as follows

<template>
...
 <ChjsDoughnutChart :data="data" :labels="labels" :blockColor="blockColor"  />
...
</template
<script>
import ChjsDoughnutChart from "../charts/Doughnut";
@Component({
  components: { ChjsDoughnutChart },
})
.....
</script>

Here “data” and “labels” are the data members of the component

Following vue-chart post deserver a good read

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.