Topic: vue barchart API json
Hello,
I have webpage build using mdbootstrap vue where I use Datatables to fill table using standard API json. Now I want to use Bar Chart to create visualization for these data - is there any simple way to create bar chart without calling external API again ? or there is any other way to fill bar char with external json ?
Magdalena Dembna staff premium answered 5 years ago
That's a very simple example, but it really depends on what data structure you operate with:
<template>
<mdb-container>
<mdb-bar-chart
:data="barChartData"
:options="barChartOptions"
:width="600"
:height="300"
></mdb-bar-chart>
</mdb-container>
</template>
<script>
import { mdbBarChart, mdbContainer } from "mdbvue";
export default {
name: "ChartPage",
components: {
mdbBarChart,
mdbContainer
},
data() {
return {
barChartData: {
labels: [],
datasets: []
},
barChartOptions: {
responsive: false,
maintainAspectRatio: false,
scales: {
xAxes: [
{
barPercentage: 1,
gridLines: {
display: true,
color: "rgba(0, 0, 0, 0.1)"
}
}
],
yAxes: [
{
gridLines: {
display: true,
color: "rgba(0, 0, 0, 0.1)"
}
}
]
}
}
};
},
mounted() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then(res => res.json())
.then(json => {
const dict = {};
json.forEach(entry => {
if (dict[entry.userId]) dict[entry.userId]++;
else dict[entry.userId] = 1;
});
const dataset = {
label: "Number of posts",
data: Object.values(dict),
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)",
"rgba(170, 40, 64, 0.2)",
"rgba(90, 90, 64, 0.2)",
"rgba(90, 255, 64, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderWidth: 1
};
this.barChartData = {
...this.barChartData,
labels: Object.keys(dict),
datasets: [dataset]
};
});
}
};
</script>
k3s4 commented 5 years ago
and if I want to have this bar chart live update? simply setInterval in javascript ?
Magdalena Dembna staff premium commented 5 years ago
The chart will update when you update data prop - although remember to update the entire value, not just one key in order to trigger rerender. So yes, simple setInterval which calls API every few seconds will do.
Magdalena Dembna staff premium answered 5 years ago
If you want to call API only once I would suggest making that call in mounted
hook, and create two methods which format the data - one for data tables (columns and rows) and the other one for bar chart (datasets). There is no built-in method for calling an API inside the chart component, but because it has data watchers, it will handle rendering async data.
Kind regards,
Magdalena
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- User: Free
- Premium support: No
- Technology: MDB Vue
- MDB Version: 6.3.0
- Device: Windows
- Browser: Chrome
- OS: Windows 10
- Provided sample code: No
- Provided link: No