Vue3 Composition API下vue-chartjs响应式数据更新问题求助
解决Vue3 + vue-chartjs柱状图响应式更新问题
问题根源
- 图表组件中的
chartData仅在初始化时读取了一次props.userHours数据,后续父组件传递的userHours变化时,chartData不会自动同步更新 - 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>
父组件补充说明
- 当前
memberHours使用reactive创建的响应式对象状态正常,无需修改 - 如果
project或projectMembers是响应式数据,建议将initHours改为computed属性,确保初始数据能随依赖变化自动更新
内容的提问来源于stack exchange,提问作者aerowei
相关产品推荐
相关产品推荐

