As title, I'm trying to load Axios data in Vue apexcharts (line chart) using vue2. I've read the apexcharts' document, but still can't figure out how to pass the data into the chart. I would like to have the date as x-axis, and others as values in the line chart.
Also, I've checked in vue devtools, it seems that the data is passed successfully?
My data format is like this:
follower = [
{
date: '2021-11-10',
follower: 2000,
following: 500,
media: 150
}
{
date: '2021-11-11',
follower: 2000,
following: 500,
media: 150
}
]
My chart initialization:
<template>
<apexchart
ref="sample"
width="500"
type="area"
:options="chartOptions"
:series="series"
>
</apexchart>
</template>
export default {
name: "FollowerLineApex",
components: {
apexcharts: VueApexCharts,
},
data: function() {
return {
series: [{
name: 'test',
data: []
}],
chartOptions: {
chart: {
height: 350,
type: 'area',
},
dataLabels: {
enabled: true
},
title: {
text: 'Example-1',
},
xaxis: {
type: "datetime"
},
}
}
},
Below is my code in Axios part:
created: function () {
this.getData()
},
methods: {
getData() {
this.$axios.get('/api/')
.then(res => {
this.series = [{
data: res.data["follower"]
}]
console.log(this.series)
this.$refs.sample.updateOptions({
series: [{
data: this.series
}]
})
})
.catch(err => {
console.log(err);
})
}
},
Your data isn't formatted correctly. You need to format the data you get from your api before you pass it to your chart's series. Your datetime
xaxis chart should be formatted as an array of x,y coordinates. Described here https://apexcharts.com/docs/series/
Example:
[
{
x: 10,
y: 20,
},
{
x: 100,
y: 50,
},
]
Working sandbox example
https://codesandbox.io/s/vue-basic-example-forked-r26j6?file=/src/components/Chart.component.vue
<template>
<div class="app">
<apexcharts
width="500"
height="350"
type="area"
:options="chartOptions"
:series="series"
></apexcharts>
</div>
</template>
<script>
import VueApexCharts from "vue-apexcharts";
export default {
name: "Chart",
components: {
apexcharts: VueApexCharts,
},
data: function () {
return {
follower: [
{
date: "2021-11-10",
follower: 2000,
following: 500,
media: 150,
},
{
date: "2021-11-11",
follower: 2000,
following: 500,
media: 30,
},
],
series: [
{
name: "test",
data: [],
},
],
chartOptions: {
chart: {
height: 350,
type: "area",
},
dataLabels: {
enabled: true,
},
title: {
text: "Example-1",
},
xaxis: {
type: "datetime",
},
},
};
},
created: function () {
this.getData();
},
methods: {
getData() {
// TODO Axios to get data here.
// Format data correctly
let formattedData = this.follower.map((e, i) => {
return {
x: e.date,
y: e.media,
};
});
// update the series with axios data
this.series = [
{
name: "test",
data: formattedData,
},
];
},
},
};
</script>