首页 > 解决方案 > 如何使用 vue-apexcharts 将数据更新为饼图

问题描述

我想用 vue-apexcharts 创建饼图。我有来自 API 的数据,但我不知道如何更新图表的数据。

 mounted() {
    axios
      .get("/data/episodes.json")
      .then(response => {
         console.log(response);
     });
  }

我要创建的图表是这样的

在此处输入图像描述

标签: apivue.jsvuejs2vue-componentpie-chart

解决方案


这是我对做的理解,...

首先,您必须定义图表的数据和选项值。

components: {
    apexchart: VueApexCharts,
  },
  data: {
    series: [],
    chartOptions: {
      chart: {
        width: 380,
        type: "pie",
      },
      labels: [],
      responsive: [
        {
          breakpoint: 480,
          options: {
            chart: {
              width: 200,
            },
            legend: {
              position: "bottom",
            },
          },
        },
      ],
    },
  },

现在在挂载时,您已经调用您的 api 来获取数据并更新图表信息。像这样......我在想你的服务器会返回一个具有值和键的对象数组。

 mounted() {
    axios.get("/data/episodes.json").then((response) => {
      for (let i = 0; i < response.data.length; i++) {
        this.data.series.push(response.data[i].value);
        this.data.chartOptions.labels.push(response.data[i].key);
      }
    });
  },

最后,您必须将图表组件添加到 vue 模板中。像这样。

<div id="chart">
    <apexchart type="pie" width="380" :options="chartOptions" :series="series"></apexchart>
</div>

完毕,

问我是否不清楚。


推荐阅读