在 vue apexcharts 中加载 axios 数据

Load axios data in vue apexcharts

作为标题,我正在尝试使用 vue2 在 Vue apexcharts(折线图)中加载 Axios 数据。 我已经阅读了 apexcharts 的文档,但仍然无法弄清楚如何将数据传递到图表中。我希望日期为 x-axis,其他为折线图中的值。

另外,我在vue devtools中查看过,好像数据传递成功了?

我的数据格式是这样的:

follower = [
  {
    date: '2021-11-10',
    follower: 2000,
    following: 500,
    media: 150
  }
  {
    date: '2021-11-11',
    follower: 2000,
    following: 500,
    media: 150
  }
]

我的图表初始化:

 <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"
        },
     }
  }

},

下面是我在 Axios 部分的代码:

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

您的数据格式不正确。在将数据传递给图表系列之前,您需要格式化从 api 获得的数据。您的 datetime x 轴图表应格式化为 x、y 坐标数组。此处描述https://apexcharts.com/docs/series/

示例:

  [
    {
      x: 10,
      y: 20,
    },
    {
      x: 100,
      y: 50,
    },
  ]

工作沙箱示例

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>

您已将 VueApexCharts 组件注册为 apexcharts(复数),因此您应该在模板中使用 <apexcharts>(复数)或将其注册为 apexchart...

components: {
  apexchart: VueApexCharts
}

根据the documentation,您不需要手动调用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.

不过您需要做的是将数据格式化为图表可以使用的内容

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()
}