Vue
VuePosts

Use and Integration of Chart.js in Vue


Use and Integration of Chart.js in Vue - webisworld - New Best - 101

Introduction

vue-chartjs lets you use Chart.js without much hassle inside Vue. It’s perfect for people who need simple charts up and running as fast as possible. we’ll use vue-chartjs package in this blog, to add chartjs in vue, vue-chartjs is a wrapper for Chart.js in Vue. It enables you to easily create reusable chart components.

Installation

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

YARN yarn add vue-chartjs chart.js

Example

LineChart.js
import { Line, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
  extends: Line,
  mixins: [reactiveProp],
  props: ['options'],
  mounted () {
    // this.chartData is created in the mixin.
    // If you want to pass options please create a local options object
    this.renderChart(this.chartData, this.options)
  }
}
RandomChart.vue
<template>
  <div class="small">
    <line-chart :chart-data="datacollection"></line-chart>
    <button @click="fillData()">Randomize</button>
  </div>
</template>

<script>
  import LineChart from './LineChart.js'

  export default {
    components: {
      LineChart
    },
    data () {
      return {
        datacollection: null
      }
    },
    mounted () {
      this.fillData()
    },
    methods: {
      fillData () {
        this.datacollection = {
          labels: [this.getRandomInt(), this.getRandomInt()],
          datasets: [
            {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [this.getRandomInt(), this.getRandomInt()]
            }, {
              label: 'Data One',
              backgroundColor: '#f87979',
              data: [this.getRandomInt(), this.getRandomInt()]
            }
          ]
        }
      },
      getRandomInt () {
        return Math.floor(Math.random() * (50 - 5 + 1)) + 5
      }
    }
  }
</script>

<style>
  .small {
    max-width: 600px;
    margin:  150px auto;
  }
</style>

Share this page on:

Was this page helpful ?

Let us know how we did!

Subscribe Email Updates

to get latest update