Vue.js中Axios API调用的ChartJS加载错误

uxh89sit  于 2023-05-17  发布在  Chart.js
关注(0)|答案(1)|浏览(142)

我正在尝试为Vue.JS中的 Jmeter 板渲染图表,我有一个flask API设置为虚拟后端。
我正在学习www.example.com上的教程https://vue-chartjs.org/guide/#chart-with-api-data,但在渲染我的可视化时遇到了问题。
我的组件代码是:

<template>
  <Bar
    v-if="loaded"
    :data="chartData"
  />
</template>

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

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

export default {
  name: 'BarChart',
  components: { Bar },
  data: () => ({
    loaded: false,
    chartData: null
  }),
  async mounted () {
    this.loaded = false

    axios.get('/genres')
      .then((res) => {
        console.log(res.data)
        this.chartData = { labels: res.data.labels, dataset: [{ data: res.data.data }] }
        this.loaded = true
      })
      .catch((err) => {
        console.error(err)
      })
  }
}
</script>

我在控制台中得到以下内容:

handled error during execution of mounted hook 
  at <Anonymous ref=fn<reforwardRef> type="bar" data= Object  ... > 
  at <Bar key=0 data= Object > 
  at <BarChart> 
  at <AboutView onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy(Object) > > 
  at <RouterView> 
  at <App>
w

ils.ts:60 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')
    at setDatasets (utils.ts:60:1)
    at cloneData (utils.ts:97:1)
    at renderChart (chart.ts:35:1)
    at eval (runtime-core.esm-bundler.js:2756:1)
    at callWithErrorHandling (runtime-core.esm-bundler.js:173:1)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:182:1)
    at hook.__weh.hook.__weh (runtime-core.esm-bundler.js:2731:1)
    at flushPostFlushCbs (runtime-core.esm-bundler.js:359:1)
    at flushJobs (runtime-core.esm-bundler.js:413:1)

我不知道这些错误是从哪里来的,因为我对JS/Vue/Chart.JS很陌生,所以任何帮助都将不胜感激!

hvvq6cgz

hvvq6cgz1#

错误来自vue-chartjs;更准确地说,是从函数setDatasets的第60行开始的,该函数在文件utils.ts中定义。
如果您更改代码的以下行,问题很可能得到解决。

this.chartData = { labels: res.data.labels, dataset: [{ data: res.data.data }] }

指定datasets而不是dataset,如下所示:

this.chartData = { labels: res.data.labels, datasets: [{ data: res.data.data }] }

如果这没有帮助,则需要检查res.data.data的结构。确保它符合formats expected by Chart.js之一。

相关问题