Vue项目使用vue-chart-3与chart.js无法正常渲染堆叠柱状图
问题根因
- 堆叠配置放错位置:写在组件导出根节点的
options字段不会被vue-chart-3读取,属于无效代码 - 配置传参结构错误:
useBarChart钩子要求图表配置直接传入options字段,自定义的config返回结构不符合钩子参数要求 - 数据格式错误:当前dataset用的是浮动柱状图要求的
[最小值, 最大值]数组格式,普通堆叠柱状图要求每个数据点传单个数值,格式不匹配会导致堆叠规则失效 - 额外问题:三个数据集用了完全相同的背景色,就算堆叠成功也看不出分层效果
正确配置位置
堆叠所需的scales.x.stacked: true、scales.y.stacked: true配置,必须放在传入useBarChart钩子的options.scales节点下,才能被chart.js正确识别。
修正后完整可用代码
脚本部分
import { Chart, registerables } from 'chart.js'; import { BarChart, useBarChart } from 'vue-chart-3'; import { computed } from 'vue'; Chart.register(...registerables); export default { name: 'StackedBarChart', components: { BarChart, }, setup() { // 所有图表配置统一在此定义 const chartOptions = { plugins: { title: { display: true, text: 'Chart.js 堆叠柱状图示例', }, }, responsive: true, scales: { x: { stacked: true, }, y: { stacked: true, }, }, }; const chartData = computed(() => ({ labels: ['Paris', 'Nîmes', 'Toulon', 'Perpignan', 'Autre'], datasets: [ { label: '数据集1', // 普通堆叠柱使用单值数据,不要传[min,max]数组 data: Array.from({length: 5}, () => Math.floor(Math.random() * 100)), backgroundColor: '#77CEFF', }, { label: '数据集2', data: Array.from({length: 5}, () => Math.floor(Math.random() * 100)), backgroundColor: '#0079AF', }, { label: '数据集3', data: Array.from({length: 5}, () => Math.floor(Math.random() * 100)), backgroundColor: '#123E6B', }, ], })); const { barChartProps, barChartRef } = useBarChart({ chartData, options: chartOptions }); return { barChartProps, barChartRef, }; } };
样式部分
.svg-inline--fa { display: var(--fa-display, inline-block); height: 1em; overflow: visible; vertical-align: -0.125em; }
模板部分
<template> <div class="col-xl-4"> <div class="card mb-4"> <div class="card-header"> <svg class="svg-inline--fa fa-chart-area me-1" aria-hidden="true" focusable="false" data-prefix="fas" data-icon="chart-area" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg="" > <path fill="currentColor" d="M64 400C64 408.8 71.16 416 80 416H480C497.7 416 512 430.3 512 448C512 465.7 497.7 480 480 480H80C35.82 480 0 444.2 0 400V64C0 46.33 14.33 32 32 32C49.67 32 64 46.33 64 64V400zM128 320V236C128 228.3 130.8 220.8 135.9 214.1L215.3 124.2C228.3 109.4 251.4 109.7 263.1 124.8L303.2 171.8C312.2 182.7 328.6 183.4 338.6 173.4L359.6 152.4C372.7 139.3 394.4 140.1 406.5 154.2L472.3 231C477.3 236.8 480 244.2 480 251.8V320C480 337.7 465.7 352 448 352H159.1C142.3 352 127.1 337.7 127.1 320L128 320z" ></path> </svg> 堆叠柱状图示例 </div> <div class="card-body"> <div style="width: 100%"> <BarChart v-bind="barChartProps" /> </div> </div> </div> </div> </template>
补充说明
如果需要实现浮动效果的堆叠柱状图,保留[min,max]数组格式的数据即可,堆叠配置位置不变。
内容的提问来源于stack exchange,提问作者Jaydeep Kesharia
相关产品推荐
相关产品推荐

