Hello, web developers! In this article, we'll see how to create a bar chart in vue 3 using vue-chartjs. Here, we'll install vue-chartjs and chart.js for dynamic bar charts in vue 3. vue-chartjs is a wrapper for Chart.js in Vue. You can easily create reusable chart components.
You can install it using the pnpm, yarn, and npm commands. It provides every chart type that is available in Chart.js is exported as a named component.
Create Bar Chart in Vue 3 using vue-chartjs
In this step, we'll install vue 3 using the following command.
npm init vue@latest
cd your-project-name
npm install
Then, we'll install vue-chartjs and chart.js dependency using the following command.
npm install vue-chartjs chart.js
Next, we'll create a component and import a bar chart.
src/App.vue
<template>
<BarChart />
</template>
<script>
import BarChart from './components/Bar.vue'
export default {
name: 'App',
components: {
BarChart
}
}
</script>
src/components/Bar.vue
<template>
<Bar
:chart-options="chartOptions"
:chart-data="chartData"
:chart-id="chartId"
:dataset-id-key="datasetIdKey"
:plugins="plugins"
:css-classes="cssClasses"
:styles="styles"
:width="width"
:height="height"
/>
</template>
<script>
import { Bar } from 'vue-chartjs/legacy'
import {
Chart as ChartJS,
Title,
Tooltip,
Legend,
BarElement,
CategoryScale,
LinearScale
} from 'chart.js'
ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)
export default {
name: 'BarChart',
components: {
Bar
},
props: {
chartId: {
type: String,
default: 'bar-chart'
},
datasetIdKey: {
type: String,
default: 'label'
},
width: {
type: Number,
default: 400
},
height: {
type: Number,
default: 400
},
cssClasses: {
default: '',
type: String
},
styles: {
type: Object,
default: () => {}
},
plugins: {
type: Array,
default: () => []
}
},
data() {
return {
chartData: {
labels: [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: [40, 20, 12, 39, 10, 40, 39, 80, 40, 20, 12, 11]
}
]
},
chartOptions: {
responsive: true,
maintainAspectRatio: false
}
}
}
}
</script>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>How to Create Bar Chart in Vue 3 using vue-chartjs - Websolutionstuff</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Now, run the vue 3 application using the following command.
npm run dev
Output:
You might also like:
Here you will learn how to get random records from DB in laravel using the inRandomOrder() method. Explore an...
Nov-10-2023
Hello All, In this post we will see helper function example in laravel, Laravel provide in-buit global "hel...
Jun-22-2021
Scheduling tasks using cron jobs in Laravel is a powerful way to automate repetitive processes like sending emails, clea...
Jan-14-2025
Greetings, developers! If you've encountered the frustrating "Laravel Mix is not recognized as an internal...
Dec-29-2023