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

Vue-chartjs中props变化时如何更新图表?新手技术求助

解决Vue3中vue-chartjs props变化不更新图表的问题

问题分析

你的代码存在两个关键问题:

  1. DoughnutChart中chartData是一次性创建的普通对象,没有和props.chartData建立响应式关联,当props更新时不会自动重新生成新的图表数据
  2. Card.vue模板中传递props时错误使用了this.scheda,Vue模板中无需加this

修复步骤

1. 修改Card.vue的模板

将模板中的this.scheda改为scheda:

<template>
  <DoughnutChart type="abcd" :chartData="scheda"/>
</template>

2. 修改DoughnutChart.js,让图表数据响应props变化

导入computed创建响应式的图表数据,确保props更新时自动生成新的图表数据:

import { defineComponent, h, computed } from 'vue'

import { Doughnut } from 'vue-chartjs'
import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    ArcElement,
    CategoryScale
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)

export default defineComponent({
    name: 'DoughnutChart',
    components: {
        Doughnut
    },
    props: ['type', 'chartData'],
    setup(props) {
      // 使用computed创建响应式图表数据,props变化时自动重新计算
      const chartData = computed(() => ({
        labels: ['A', 'B'],
        datasets: [
          {
            backgroundColor: ["#ff3333", "#131b2e"],
            cutout: "75%",
            borderWidth: 0,
            data: [props.chartData.value, (100 - props.chartData.value)]
          }
        ]
      }))  

      const chartOptions = {
        plugins: {
          legend: {
              display: false
          }
        },
        responsive: true,
        maintainAspectRatio: false
      }  

      return () =>
        h(Doughnut, {
          chartData: chartData.value,
          chartOptions
        })
    }
})

原理说明

  • computed会监听props.chartData的变化,每当props.chartData更新时,会自动重新生成新的chartData对象
  • 新的chartData传递给Doughnut组件后,vue-chartjs会检测到数据变化并自动更新图表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:05:25