You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中Axios调用API加载ChartJS图表出现渲染错误

Vue-Chartjs图表渲染失败:TypeError: Cannot read properties of undefined (reading 'map')

你的错误根源是Chart.js数据格式不匹配:你在构造chartData时写了单数的dataset,但Chart.js要求的是复数形式datasets。这会导致内部代码尝试对undefined执行map操作,触发你看到的报错。

修正后的组件代码

<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 () {
    try {
      const res = await axios.get('/genres')
      console.log(res.data)
      // 修正:把dataset改为datasets,同时为数据集添加label(可选但推荐)
      this.chartData = { 
        labels: res.data.labels, 
        datasets: [{ 
          label: '分类数据',
          data: res.data.data 
        }] 
      }
      this.loaded = true
    } catch (err) {
      console.error(err)
      // 错误时设置默认数据,避免页面一直空白
      this.chartData = {
        labels: [],
        datasets: [{ label: '数据加载失败', data: [] }]
      }
      this.loaded = true
    }
  }
}
</script>

额外注意事项

  • 确认Flask API返回的res.data结构正确:必须包含labels(数组类型)和data(数组类型)字段
  • 推荐用async/await替代.then()写法,让异步逻辑更易读
  • 错误处理中设置默认数据,能避免图表一直不渲染,提升用户体验

内容的提问来源于stack exchange,提问作者Jack Gee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:08:18