如何从API中获取数据以在Vuejs中使用chartjs显示图表

w46czmvw  于 2023-10-18  发布在  Chart.js
关注(0)|答案(3)|浏览(166)

我是新的Vuejs,我想知道如何从我的API获取数据来显示图表。
下面是我的代码,我已经使用数据作为“日期和挑战”,并直接向它提供数据,但现在我想调用我的API,并从它向“日期和挑战”提供数据。
代码,我用它来显示图表没有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)时,我都会在浏览器的控制台中获取数据,但进一步来说,我不知道如何Map它并使用这些数据来提供“日期和挑战”以显示图表。
以下是我的API:
我的API,其中包含数据:https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs
请有人帮助我显示图表使用我的API在我的代码。

hpcdzsge

hpcdzsge1#

您试过这种吗?

解决方案1

添加async/await,以便它将等待数据填充到datachallege

async mounted () {
    let result = await axios.get('https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs')
    this.date = result.data.date
    this.challenge = result.data.challenge

    // 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  }%`
                }
              }
            }
          ]
        }
      }
    })
  }

也可以从其他组件的API中获取数据,并将datechallege作为props发送给该组件。

解决方案2

我假设您有图表组件chart.vue

chart.vue

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

<script>

export default {
  name: 'Chart',

  props: ['date', 'challenge],

  data: () => ({

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

在其他组件中,导入chart.vue

<template>
    <div>
        <Chart v-if="!isLoading" :date="date" :challenge="challenge" />
    </div>
</template>

<script type="text/javascript">
    import Chart from 'PATH TO chart.vue'
    export default {
        components: {
            Chart
        },
        data () => ({
            date: [],
            challenge: [],
            isLoading: false
        }),
        methods: {
            async getData () {
                this.isLoading = true
                let result = await axios.get(API URL)
                this.date = result.data.date
                this.challenge = result.data.challenge
                this.isLoading = false
            }
        },
        mounted () {
            this.getData()
        }
    }
</script>

chart.vue中,从data中删除datechallege,因为您将拥有props,因为最佳实践propsdata不能具有相同的属性名称。
在导入chart.vue的其他组件中,只需像往常一样获取数据。
当我在我的项目中使用chartjs时,我总是添加v-if,它会让axios首先获取数据,然后重新挂载图表组件。因为我猜chartjs对vuejs的数据变化没有React,所以需要先更新数据,然后再重新挂载。

k2arahey

k2arahey2#

终于,我得到了答案!
我分享,我是如何做到这一点,甚至你可以做同样的,以可视化图表与您的API数据。

<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>
bvn4nwqk

bvn4nwqk3#

您可以使用vue-chartjs,它是Vue中Chart.js的 Package 器。
安装在npm包管理器上。

npm install vue-chartjs chart.js

根据文档,从异步API端点访问数据时存在一个常见问题:
这种方法的问题在于Chart.js会尝试同步地呈现图表和访问图表数据,因此图表会在API数据到达之前挂载
为了防止这种情况,简单的v-if是最好的解决方案。下面的Vue组件使用一个布尔变量在数据到达之前停止图表挂载。

<template>
  <div>
    <h1>Stock Data</h1>
    <!-- The v-if is used to conditionally render a block -->
    <Bar id="my-chart-id" v-if="loaded" :options="chartOptions" :data="chartData" :width="600" />
  </div>
</template>

<script>
import { Bar } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChart',
  components: { Bar },
  data: () => ({
    // Prevents chart to mount before the API data arrives
    loaded: false,
    chartData: {
      labels: [],
      datasets: [
        {
          label: 'My Label',
          data: [],
          backgroundColor: 'rgba(54, 162, 235, 0.2)'
        }
      ]
    },
    chartOptions: {
      responsive: true
    }
  }),
  async mounted() {
    const apiUrl = 'http://localhost:8000/data'

    // Make an HTTP request to fetch the data from the API endpoint
    await fetch(apiUrl)
      .then((response) => response.json())
      .then((data) => {
        // Extract data from the API response and update the chartData
        this.chartData.labels = data.map((stock) => stock.date)
        this.chartData.datasets[0].data = data.map((stock) => stock.value)

        // Allow the chart to display the data from the API endpoint
        this.loaded = true
      })
      .catch((error) => {
        console.error('Error fetching data:', error)
      })
  }
}
</script>

关键是只有当数据成功到达时才呈现条形图。这是通过将loaded变量设置为true来实现的。请注意,每当新数据到达时,您需要重新加载页面。

相关问题