vue js charts

·

2 min read

Vue is a very loved and famous UI framework now a days. While working on any type of Web development sometimes we need to render charts in our application. We will see how we can render charts in Vue application. By following these steps we don't need to download any library from the npm.

Our first step is to use chart js cdn library in application index.html file exist in public directory.

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

now in component add a div along with canvas tag in which we will render charts

<div>
    <canvas id="chartdiv"></canvas>
</div>

Now in the script tag define chart variable to use all the functions/features provided by chart JavaScript library like this:

declare const Chart: any;

Now in methods property in our component we will add method to generate charts:

generateChart() {
    const self = this;
    if (!document.getElementById('chartdiv')) {
      return;
    }
    const canvasElem = document.getElementById('chartdiv');
    const ctx = canvasElem.getContext('2d');
    this.chartObj = new Chart(ctx, {
      // The type of chart we want to create
      type: 'pie',

      // The data for our dataset
      data: labels: ['January', 'February', 'March'],
    datasets: [{
      label: 'January',
      backgroundColor: 'yellow',
      borderColor: 'rgb(255, 99, 132)',
      data: [5, 10, 15]
    },
    {
      label: 'Febrauary',
      backgroundColor: 'brown',
      borderColor: 'rgb(255, 99, 132)',
      data: [20, 25, 30]
    }, {
      label: 'March',
      backgroundColor: 'purple',
      borderColor: 'rgb(255, 99, 132)',
      data: [35, 43, 45]
    }],

      options: {
        legend: {
          display: true,
          onClick: (e, legendItem) => {
            const labelIndex = legendItem.datasetIndex;
            // here our click handler on label click event
          }
        },
        onClick(e) {
          const element = this.getElementAtEvent(e);
          if (element && element.length > 0) {
            const datasetLabel = this.config.data.datasets[element[0]._datasetIndex].label;
            const data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index];
            // here our chart legends click handler
          }
        }
      }
    });
  }

In generateChart() method we are accessing the element in which we will render chart along with data provided in the chart. The best use of declare Chart variable declare const Chart: any;. we can implement any feature while generating charts in our Vue application as per documentation provided by chart.js. We don't need to import/download any library from npm. Now the last step is to use generateChart() method in component created() hook like this:

this.generateChart();