Create Scatter chart component in Vue


Create component

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

//ScatterChart.js
import { Scatter, mixins } from 'vue-chartjs'

export default {
  extends: Scatter,
  mixins: [mixins.reactiveProp],
  name: 'ScatterChart',
  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 Scatter 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">
    <ScatterChart :chartData="chartdata" :options="options" />
  </div>
</template>

<script>
// @ is an alias to /src
import ScatterChart from '@/components/ScatterChart'
export default {
  name: "Scatter",
  components: { ScatterChart
  },
  data (){
    return {
    chartdata: {
         datasets: [{
        label: 'Scatter Dataset 1',
        fill: false,
        borderColor: '#f87979',
        backgroundColor: '#f87979',
        data: [{
          x: -2,
          y: 4
        }, {
          x: -1,
          y: 1
        }, {
          x: 0,
          y: 0
        }, {
          x: 1,
          y: 1
        }, {
          x: 2,
          y: 4
        }]
      },
      {
        label: 'Scatter Dataset 2',
        fill: false,
        borderColor: '#7acbf9',
        backgroundColor: '#7acbf9',
        data: [{
          x: -2,
          y: -4
        }, {
          x: -1,
          y: -1
        }, {
          x: 0,
          y: 1
        }, {
          x: 1,
          y: -1
        }, {
          x: 2,
          y: -4
        }]
      }]
    },
    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

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.