Home > Software design >  Load axios data in vue apexcharts
Load axios data in vue apexcharts

Time:11-12

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);
        })
  }
},

CodePudding user response:

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>

CodePudding user response:

You've registered the VueApexCharts component as apexcharts (plural) so you should either be using <apexcharts> (plural) in your template or register it as apexchart...

components: {
  apexchart: VueApexCharts
}

As per the documentation, you do not need to manually call updateOptions...

Updating your Vue chart data is simple. You just have to update the series props which you pass to the <apexchart> component and it will automatically trigger event to update the chart.

What you do need to do though is format the data into something the chart can use

data: () => ({
  followerData: [],
  chartOptions: { /* same as you already have */ }
}),
computed: {
  // compute series data from you API results
  series: ({ followerData }) => {
    const series = followerData.reduce((map, { date, ...points }) => {
      Object.entries(points).forEach(([ name, point ]) => {
        const s = (map.has(name) ? map : map.set(name, [])).get(name)
    
        s.push({
          x: date,
          y: point
        })
      })
      return map
    }, new Map())

    return Array.from(series.entries(), ([ name, data ]) => ({
      name,
      data
    }))
  }
},
methods: {
  async getData() {
    const { data } = await this.$axios.get("/api/")
    this.followerData = data
  }
},
created () {
  this.getData()
}
  • Related