Contents
Description:
A light-weight and simple Chart.js wrapper in Vue.js, compatible for Vue.js version 2 and 3. This component is re-written version of Chart.js 3.
You might also like:
Vue3-Charts: Highly Customizable SVG-based Chart Library For Vue.js 3Donut Chart For Vue.js Created Using Pure CSS OnlySimple And Intuitive Gantt Chart For Vue.js – vue-ganttastic
How can I use it?
1. Install the component with npm or yarn.
#npm
npm i vue-chart-3
#yarn
yarn add vue-chart-3
2. Import the required component in your project.
import { computed, ref } from “vue”;
import { shuffle } from “lodash”;
import { DoughnutChart } from “vue-chart-3”;
import { Chart, ChartData, ChartOptions, registerables } from “chart.js”;
3. Then, register the component and create the chart.
Chart.register(…registerables);
export default {
name: “App”,
components: { DoughnutChart },
setup() {
const dataValues = ref([30, 40, 60, 70, 5]);
const toggleLegend = ref(true);
const doughnutRef = ref();
const testData = computed<ChartData<“doughnut”>>(() => ({
labels: [“Paris”, “Nîmes”, “Toulon”, “Perpignan”, “Autre”],
datasets: [
{
data: dataValues.value,
backgroundColor: [
“#77CEFF”,
“#0079AF”,
“#123E6B”,
“#97B0C4”,
“#A5C8ED”,
],
},
],
}));
const options = computed<ChartOptions<“doughnut”>>(() => ({
scales: {
myScale: {
type: “logarithmic”,
position: toggleLegend.value ? “left” : “right”,
},
},
plugins: {
legend: {
position: toggleLegend.value ? “top” : “bottom”,
},
title: {
display: true,
text: “Chart.js Doughnut Chart”,
},
},
}));
function shuffleData() {
dataValues.value = shuffle(dataValues.value);
console.log(doughnutRef.value.chartInstance);
}
function switchLegend() {
toggleLegend.value = !toggleLegend.value;
}
return {
shuffleData,
switchLegend,
testData,
options,
doughnutRef,
};
},
};
4. Create the template, where the chart will be displayed.
<template>
<div style=”width: 400px”>
<div style=”display: flex; justify-content: center”>
<button type=”button” @click=”shuffleData”>Shuffle</button>
<button type=”button” @click=”switchLegend”>Swicth legends</button>
</div>
<DoughnutChart ref=”doughnutRef” :chartData=”testData” :options=”options” />
</div>
</template>
5. Add some CSS.
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
Thanks for reading.
The post A Chart.js 3 Wrapper In Vue.js Version 2 And 3 appeared first on Lipku.com.