如何在Vue.js中使用Chart.js从API获取数据以显示图表 [英] How to get Data from API to display chart using chartjs in Vuejs

查看:92
本文介绍了如何在Vue.js中使用Chart.js从API获取数据以显示图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Vuejs的新手,我想知道如何从API中获取数据以显示图表.

I am new to Vuejs and i wanna know how to fetch data from my API to display chart.

下面是我的代码,其中我已将数据用作日期和挑战".并直接将数据提供给它,但是现在我想调用我的API并将数据从其中提供给约会和挑战".

Below is my code, where i have used data as "date and challenge" and have fed data directly to it, but now i want to call my API and feed the data from it to "date and challenge".

我使用它来显示没有API的图表的代码:

Code that i have used it to display chart without API:

<template>
  <canvas id="mychart" width="550" height="300"></canvas>
</template>

<script>

export default {
  name: 'Chart',
  data: () => ({
    date: [
      1600934100.0,
      1602009600.0,
      1602747060.0,
      1603050158.390939,
      1603305573.992575
    ],
    challenge: [
      9.0,
      9.5,
      2.5,
      11.52,
      12.4
    ]
  }),
  mounted () {
    // eslint-disable-next-line no-unused-vars
    const data = this.date.map((date, index) => ({
      x: new Date(date * 1000),
      y: this.challenge[index]
    }))

    const ctx = document.getElementById('mychart').getContext('2d')
    // eslint-disable-next-line no-undef,no-unused-vars
    const Chart_2 = new Chart(ctx, {
      type: 'line',
      data: {
        datasets: [
          {
            data,
            label: 'Chart from API ',
            borderColor: '#7367F0'
          }
        ]
      },
      options: {
        scales: {
          xAxes: [
            {
              type: 'time',
              time: {
                unit: 'month',
                displayFormats: {
                  month: 'MMM YYYY'
                }
              }
            }
          ],
          yAxes: [
            {
              ticks: {
                // eslint-disable-next-line no-unused-vars
                callback (value, index, values) {
                  return `${value  }%`
                }
              }
            }
          ]
        }
      }
    })
  }
}
</script>

我知道要获取API,我们使用'axios'或'fetch',因此,每当我获取API并执行console.log(response.data)时,我都会在浏览器的控制台中获取数据,但是我不这样做知道要映射它并使用那些数据来输入日期和挑战".为了显示图表.

I know to get API we use 'axios' or 'fetch' , so whenever i get API and just do console.log(response.data) i will get my data in the console in my browser, but further i dont know to map it and use those data to feed "date and chalenge" in order to display chart.

这是我的API:

我的其中包含数据的API: https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs

My API which contains data in it: https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs

请有人在我的代码中使用我的API来帮助我显示图表.

Please someone help me to display chart by using my API in my code.

推荐答案

最后,我得到了答案Hoorah!

Finally, I got the answer Hoorah!

我正在分享,我什至做到了,即使您也可以这样做,以便用您的API数据可视化图表.

I am sharing, how I did it even you can do the same in order to visualize chart with your API data.

<template>
  <div class="chart-container" style="position: relative; height: 25vh; width:100%;">
    <canvas id="DisplayChart" ></canvas>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'Chart_from_API',
  data () {
    return {
      myChart: []
    }
  },
  async mounted () {
    await this.$http.get('https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs') //Your API has to be given here
      .then((response) => {
        const result = response.data
        const ctx = document.getElementById('DisplayChart').getContext('2d')
        const Chart_data = []
        for (let i = 0; i < result.date.length; i++) {
          Chart_data.push({
            x_axis: moment(result.date[i], 'X').toDate(),  //To Convert Unix Timestamp into Date
            y_axis: result.challenge[i]
          })
        }
        // eslint-disable-next-line init-declarations,prefer-const
        let myChart
        if (myChart !== undefined) {
          myChart.destroy()
        }

        // eslint-disable-next-line no-undef
        myChart = new Chart(ctx, {
          type: 'line',
          data: {
            datasets: [
              {
                label: 'Chart_from_API',
                data: Chart_data,
                borderColor: '#EA5455',
                lineTension: 0
              }
            ]
          },
          options: {
            lineTension: 0,
            maintainAspectRatio: false,
            legend: {
              display: false
            },
            scales: {
              yAxes: [
                {
                  scaleLabel: {
                    display: false
                  },
                  ticks: {
                    beginAtZero: true,
                    // eslint-disable-next-line no-unused-vars
                    callback (value) {
                      return `${value  }k`    // y-axis value will append k to it
                    }
                  }
                }
              ],
              xAxes: [
                {
                  type: 'time',
                  time: {
                    unit: 'month'
                  },
                  scaleLabel: {
                    display: true,
                    labelString: ''
                  }
                }
              ]
            }
          }
        })
      })
      .catch((error) => {
        console.log(error)
      })
  }
}
</script>

这篇关于如何在Vue.js中使用Chart.js从API获取数据以显示图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆