Create Bar chart component in Vue


Data Visualization is the important part of a commercial application. There are plenty of JavaScript library available for this task. In this series of post we are discussing about Chartjs and its Vue wrapper.

Creating Component may save your time and it increase the re-usability of the code.

Create a Bar Chart component

In-order to use Chartjs charts we need multiple dependency which can be installed using one of the following methods.

 yarn add vue-chartjs chart.js
 npm install vue-chartjs chart.js --save

Create component

In the component folder of the project add the following code and name the file BarChart.js

import { Bar, mixins } from 'vue-chartjs'

export default {
  extends: Bar,  
  mixins: [mixins.reactiveProp],
  name: 'BarChart',
  props: [{
    chartdata: {
      type: Object,
      default: null
    },
    options: {
      type: Object,
      default: null
    }
  }],
  mounted() {
    this.renderChart(this.chartData, this.options)
  }
}

We have used a mixin which combine the reactive props and Bar chart from the vue-chartjs module.

Using the component

In the page component we can import component and bind the data, and options.

<template>
  <div class="flex-container">
    <BarChart :chartData="chartdata" :options="options" />
  </div>
</template>

<script>
// @ is an alias to /src
import BarChart from '@/components/BarChart'
export default {
  name: "Bar",
  components: { BarChart 
  },
  data (){
    return {
    chartdata: {
      labels: ['January', 'February'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          data: [40, 20]
        },
         {
          label: 'Data Two',
          backgroundColor: '#5885af',
          data: [140, 120]
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false
    },
    }

  }
  
};
</script>
<style>
.flex-container {
  display: flex;
}

</style>

A complete set of chart components will be available on Vue-chart-components Repository

Following vue-chartjs post may help you build app faster

Create doughnut chart component in Vuejs


Data Visualization is the important part of a commercial application. There are plenty of JavaScript library available for this task. In this series of post we are discussing about Chartjs and its Vue wrapper.

Creating Component may save your time and it increase the re-usability of the code.

Install dependencies

In-order to use Chartjs charts we need multiple dependency which can be installed using one of the following methods.


 yarn add vue-chartjs chart.js
 npm install vue-chartjs chart.js --save

Create component

In the component folder of the project add the following code and name the file Doughnut.js

import { Doughnut, mixins } from 'vue-chartjs'

export default {
  extends: Doughnut,  
  mixins: [mixins.reactiveProp],
  name: 'DoughnutChart',
  props: [{
    chartData: {
      type: Object,
      default: null
    },
    options: {
      type: Object,
      default: null
    }
  }],
  mounted() {
    this.renderChart(this.chartData, this.options)
  }
}

Using the component

In the page component we can import component and bind the data, and options.

<template>
  <div class="flex-container">
    <DoughnutChart :chartData="chartdata" :options="options" />
  </div>
</template>

<script>
// @ is an alias to /src
import DoughnutChart from '@/components/Doughnut'
export default {
  name: "Doughnut",
  components: { DoughnutChart 
  },
  data (){
    return {
    chartdata: {
      labels: ['January', 'February'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          data: [40, 20]
        },
         {
          label: 'Data Two',
          backgroundColor: '#5885af',
          data: [140, 120]
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false
    },
    }

  }
  
};
</script>
<style>
.flex-container {
  display: flex;
}

</style>

A complete set of chart components will be available on Vue-chart-components Repository

Following vue-route post may interest you

Create line chart component in Vue


Data Visualization is the important part of a commercial application. There are plenty of JavaScript library available for this task. In this series of post we are discussing about Chartjs and its Vue wrapper.

Creating Component may save your time and it increase the re-usability of the code.

Create a Line Chart component

In-order to use Chartjs charts we need multiple dependency which can be installed using one of the following methods.

 yarn add vue-chartjs chart.js
 npm install vue-chartjs chart.js --save

Create component

In the component folder of the project add the following code and name the file LineChart.js

import { Line, mixins } from 'vue-chartjs'

export default {
  extends: Line,  
  mixins: [mixins.reactiveProp],
  name: 'LineChart',
  props: [{
    chartdata: {
      type: Object,
      default: null
    },
    options: {
      type: Object,
      default: null
    }
  }],
  mounted() {
    this.renderChart(this.chartData, this.options)
  }
}

We have used a mixin which combine the reactive props and Line chart from the vue-chartjs module.

Using the component

In the page component we can import component and bind the data, and options.

<template>
  <div class="flex-container">
    <LineChart :chartData="chartdata" :options="options" />
  </div>
</template>

<script>
// @ is an alias to /src
import  LineChart   from "@/components/LineChart"
export default {
  name: "LineChart",
  components: { LineChart
  },
  data (){
    return {
    chartdata: {
      labels: ['January', 'February'],
      datasets: [
        {
          label: 'Data One',
          backgroundColor: '#f87979',
          data: [40, 20]
        },
         {
          label: 'Data Two',
          backgroundColor: '#5885af',
          data: [140, 120]
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false
    },
    }

  }
  
};
</script>
<style>

.flex-container {
  display: flex;
}
</style>

A complete set of chart components will be available on Vue-chart-components Repository

Following vue-route post may interest you

redirecting multiple routes in Vuejs


Sometimes we would like to have same route with different name, such guide to FAQ, help, how-to etc. What should we do when want to redirect same route against a bunch of routes ?. Here the alias came into picture

alias can be used in our index route file to redirect a route / a set of route to specific route. The following example will clarify this

import Vue from "vue";
 ......
Vue.use(VueRouter);
const routes = [
  {
    path: "/",
    name: "Line",
    component: LineChart,
     },   
  {
    // The redirect can also be targeting a named route:
    path: "/help",
    redirect: { name: 'About' }
  },
  {
    //redirect with aliad
    path: "/doughnut",
    name: "Doughnut",
    component: Doughnut,
    alias: ['/donut', '/dot']

  }, 
];
const router = new VueRouter({
  routes
});

export default router;

In the above router configuration I have a route doughnut which shows the doughnut chart. All I want to different routes set to this route. we redirect /doughnut route to the /donut, /dot routes. As a result all the routes are working

Following vue-route post may interest you

Redirect a route in Vue router


Sometimes we would like to have same route with different name, such guide to FAQ, help, how-to etc. Vue allow us to use the redirect feature for this purpose.

Redirect can be used in our index route file in the following format

import Vue from "vue";
 ......
Vue.use(VueRouter);
const routes = [
  {
    path: "/",
    name: "Line",
    component: LineChart,
     },   
  {
    // The redirect can also be targeting a named route:
    path: "/help",
    redirect: { name: 'About' }
  } 
];
const router = new VueRouter({
  routes
});

export default router;

In the above router configuration we redirect /help router to the named route /About. For multiple route we have to reply on alias.

Following vue-route post may interest you

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

Read local JSON file in Vuejs


Sometimes we need to read data from a local file, such as Mock Data which can be stored in the form of JSON format.

Create folder for mock data and place the JSON inside the folder.

[
   { "id": 1, "title": "work out from json", "isdone": true },
   { "id": 2, "title": "Fallback", "isdone": false }

] 

and in the component we can read the file using an import statement.

import  taskData from '@/mockData/taskData.json'

we can place the data as a state in store as follows

 state: {       
    tasks: taskData, 
  },

The following Vuex store post deserve a good read

  • Read local JSON file in Vuejs - How to read local JSON / how to read mock data from a JSON file in Vuejs
  • How to Modules in Vuex - State management in Vuejs with Vuex module store Using Typescript. All you need to know for kick start Vuex store modules
  • Vuex store ? - State management in Vuejs with Vuex store. All you need to know for kick start Vuex store

How to Modules in Vuex


So far We have been using props to pass data through parent child chain in our vuejs apps. This can be still working, we can do these data transactions and state management in a much easier way.

This is tutorial uses Typescript

Vuex Store Modules

Vuex store can be organized as modules, so that we can organize the data in a better way.Each module has its own state, mutations, actions and getters. Each state should have a type.

Products Module and interfaces

First up all create types for our state. The state is a indented to store values (array), so we have to define two types, one for state variable and another for array type.

export interface productState {
    products: Product[];
}

export interface Product {
    id: number;
    product: string;
    pk: string;
    mfr: string;
    hsn?: string;
    ts: number;
} 

We can store these types into a separate file which is recommended.

Vuex store ?


So far We have been using props to pass data through parent child chain in our vuejs apps. This can be still working, we can do these data transactions and state management in a much easier way.

What is a Vuex Store

Vuex store is state management module which helps developers to manage state of the object, and allow access data from any component through out the project.

How to add Vuex to Project

We can add Vuex to any project, by enabling the feature while creating new project or using Vue CLI as follows

vue add vuex

Components

Under the store reside under the store folder, usually in index file. A Vuex store can be made of modules or it can be standalone store with following sections

  • State – where data kept
  • mutations – which change state
  • Actions – methods which use state
  • Getters – which can access state

Chartjs for Vuejs


When it come to chart I should mention Morris chart which I start developing my very first Python Flask app. It offer pretty nice charts. But for Vue I recommend you to use Chartjs.

Vue-Chartjs

Chartjs has Vue wrapper variant (opensource) which is based on Original Chartjs. 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

Example

Here is a simple TypeScript example ( provided by the official GitHub repository)

// CommitChart.ts
import { Component, Mixins } from 'vue-property-decorator'
import { Bar, mixins } from 'vue-chartjs';
import { Component } from 'vue-property-decorator';

@Component({
    extends: Bar, // this is important to add the functionality to your component
    mixins: [mixins.reactiveProp]
})
export default class CommitChart extends Mixins(mixins.reactiveProp, Bar) {
  mounted () {
    // Overwriting base render method with actual data.
    this.renderChart({
      labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      datasets: [
        {
          label: 'GitHub Commits',
          backgroundColor: '#f87979',
          data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
        }
      ]
    })
  }
}

What Next ?

lol, create custom component for charting , so that you can use them in other projects.

One of the key point to remember that the chart component class doesn’t have a CSS and Template section. According to documentation it can’t have template section. So you have to use another component using the above component.

Following vue-chart post deserver a good read