如何从api插入数据和标签到数据集中以显示图表

时间:2019-08-05 18:05:28

标签: javascript vue.js charts

我是vuejs的新手,但我不了解如何将API数据中的数据和标签插入数据集和标签以显示多条折线图, 我在下面给出了数据模型,这就是我的API输出数据。

我在互联网上进行搜索,并且尝试了很多方法,但没有找到解决方案。我的代码在这里:.................................... ................................................... ...................................................

    <script>
      data() {
      return {
        labels: [ ],
         result:'',
         datasets: [
        {
          label: "Data One",
          data: [ ]
        },
        {
          label: "Data Two",
          data: [ ]
        }
      ]
    };
  },

    methods: {
    updateChart() {
      var self=this;
      axios
        .get("http://localhost:5000/api/" )
        .then(res => {
          // proccess the response
         //  this.datasets[0].data = res.data[0];
       //  self.result = res.data;
       //  console.log(self.result )
          this.renderChart(
            {
              labels: [],
              datasets: this.datasets
            },
            { responsive: true, maintainAspectRatio: false }
          );
        })
        .catch(function(error) {
          console.log("Error:", error);
        });
      }
     }
   </script>

   //below is my api data
        [
    [
      "2014-01-01", 
      "2014-01-01", 
      "2014-01-02", 
      "2014-01-03", 
      "2014-01-04"
    ], 
    [
      10002200, 
      10379971, 
      10123749, 
      10712250, 
      13923904
    ], 
    [
      14412854, 
      12412854, 
      14415554, 
      12415554, 
      16412854
    ]
  ]

1 个答案:

答案 0 :(得分:0)

您可以根据API响应执行以下操作:

axios
    .get("http://localhost:5000/api/" )
    .then(res => {
        //labels are the first element in the array
        this.labels = res.data[0]

        //remove the first element from the array so we don't pollute our datasets
        res.data.shift()

        //destructure the array and reduce it
        this.datasets = [...res.data].reduce((carry, arr) => {
          //push our dataset object into the carry
          carry.push({
            label: '',
            data: arr
          })

          return carry
        },[])

        //build the chart
        this.renderChart({
            labels: this.labels,
            datasets: this.datasets
        })
    })

为清楚起见,我在上面的代码中添加了注释。不过,我看不出有任何方法可以为您提供各个数据集的label