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

Vue3 Composition API下vue-chartjs响应式数据更新问题求助

解决Vue3 + vue-chartjs柱状图响应式更新问题

问题根源

  1. 图表组件中的chartData仅在初始化时读取了一次props.userHours数据,后续父组件传递的userHours变化时,chartData不会自动同步更新
  2. vue-chartjs封装的图表组件需要手动调用图表实例的update()方法,才能触发视图刷新

修改图表组件(ProjectChart)

<script setup lang="ts">
import { Bar } from "vue-chartjs"
import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    BarElement,
    CategoryScale,
    LinearScale,
} from "chart.js"
import { ref, watch, defineProps, computed } from 'vue'

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

const props = defineProps<{ userHours: Record<string, number> }>()

// 存储图表实例
const chartInstance = ref<ChartJS | null>(null)

const chartData = ref({
    labels: Object.keys(props.userHours),
    datasets: [
        {
            label: "Worker Hours per Employee",
            data: [...Object.values(props.userHours)] as number[],
            maxBarThickness: 32,
            backgroundColor: "#ffb53c",
        },
    ],
})

const chartOptions = ref({
    responsive: true,
    maintainAspectRatio: true,
    scales: {
        x: {
            grid: {
                color: "black",
            },
            ticks: {
                color: "#eee",
            },
        },
        y: {
            grid: {
                color: "black",
            },
            ticks: {
                color: "#eee",
            },
        },
    },
    legend: {
        labels: {
            fontColor: "#eee",
        },
    },
})

const chartStyles = computed(() => {
    return {
        width: "100%",
        height: "20ch",
    }
})

// 监听props.userHours变化,更新图表数据并刷新
watch(() => props.userHours, (newHours) => {
    chartData.value.labels = Object.keys(newHours)
    chartData.value.datasets[0].data = [...Object.values(newHours)] as number[]
    
    // 调用图表实例的update方法刷新视图
    chartInstance.value?.update()
}, { deep: true }) // 针对对象类型开启深度监听
</script>

<template>
    <Bar
        id="workhr-chart"
        :options="chartOptions"
        :data="chartData"
        :style="chartStyles"
        @chart-rendered="chartInstance = $event"
    >
    </Bar>
</template>

父组件补充说明

  1. 当前memberHours使用reactive创建的响应式对象状态正常,无需修改
  2. 如果project或projectMembers是响应式数据,建议将initHours改为computed属性,确保初始数据能随依赖变化自动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:25:50