Menu

Using Chart.js (Chart JS) in Vue js with TypeScript

Chart.js is awesome, has many chart types and very configurable, most of all its free.

Let’s look at how we can build it before we get started on the Vue component. We need to include the Chart.js wither via npm or by directly placing the file in your project (whatever easy).

<template>
  <canvas ref="chart"></canvas>
</template>


<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { RouteURL } from "../../../shared/constants";
import { chartColourHelper } from "../shared/ChartColourHelper";
import {
  IUsage,
  IMonthlyUsage,
  IChartData
} from "../shared/models";
declare var window: any;
declare var Chart: any;
@Component({
  components: {},
  props: {   
    usages: {
      type: Object,
      required: true
    }
    .............
    .............
  }  
})
export default class ChartComponent extends Vue {
  ctx: any;
  chart: any;
  unitName: string = "";
  created() {
   
  }

  mounted() {
    const element: any = this.$refs.chart;
    this.ctx = element.getContext("2d");
    this.buildChart();
  }

  buildChart() {
    const usages: IUsage[] = <IUsage[]>this.$props.usages;  
    var config = this.getConfig(usages);
    if(this.chart!= undefined)
        this.chart.destroy();
    this.chart = new Chart(this.ctx, config);
  }

  getConfig(usages: IUsage[]) {
    const labels: string[] = this.getLabels(usages[0].MonthlyEnergyUsages);
    return {
      type: "line",
      data: {
        labels: labels,
        datasets: this.getDatasets(usages)
      },
      options: this.getOptions()
    };
  }

  getLabels(energyUsages: IMonthlyEnergyUsage[]): string[] {
    let result: string[] = [];
    for (let energyUsage of energyUsages)
      result.push(energyUsage.MonthNameLetter);

    return result;
  }

  getDatasets(usages: IBuildingMonthlyEnergyUsage[]): IChartData[] {
    let result: any[] = [];
    let i: number = 0;
    for (let usage of usages) {
      let data: number[] = [];
      for (let monthly of usage.MonthlyEnergyUsages) {
        data.push(monthly.Usage);
      }

      result.push({
        label: usage.BuildingName,
        backgroundColor: this.getColour(usages, i),
        borderColor: this.getColour(usages, i),
        pointRadius: 0,
        lineTension: 0,
        data: data,
        fill: false
      });

      i++;
    }

    return result;
  }

  getColour(usages: IUsage[], i: number): string {
    if (usages.length > 1) 
     return chartColourHelper.Colours()[i];

    return "#3E4852";
  }

  getOptions(): any {
    return {
      legend: { display: true },
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        xAxes: [
          {
            gridLines: {
              drawBorder: false,
              display: false
            },
            display: true,
            scaleLabel: {
              display: true
              labelString: 'Month'
            },
            
          }
        ],
        yAxes: [
          {
            ticks: {
                beginAtZero: true               
            },
            display: true,
            scaleLabel: {
              display: true
              labelString: 'Usage'
            }
          }
        ]
      }
    };
  }
}
</script>

 

Leave a comment