Vue Chart.js Line组件报错:class does not have id: [object Object]
问题:使用vue-chartjs的Line组件报错
Uncaught Error: class does not have id: [object Object] 使用vue-chartjs的Line组件时触发如下错误,但Bar组件可正常运行,附上报错堆栈及组件代码,请求排查问题:
报错堆栈
core.typedRegistry.js:38 Uncaught Error: class does not have id: [object Object] at TypedRegistry.register (core.typedRegistry.js:38:13) at Registry._exec (core.registry.js:154:14) at core.registry.js:142:16 at each (helpers.core.ts:156:10) at core.registry.js:134:9 at Array.forEach (<anonymous>) at Registry._each (core.registry.js:125:15) at Registry.add (core.registry.js:26:10) at Chart.register (core.controller.js:131:14) at Chart.vue:7:9
组件代码
<script type="module"> import { Line } from 'vue-chartjs' import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, PointElement , CategoryScale, LinearScale } from 'chart.js' ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale , PointElement , Line) export default { data() { return { chartData: { labels: [ 'January', 'February', 'March' ], datasets: [ { label:"Ventes", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [40, 20, 12] } ] }, chartOptions: { responsive: true } } } , components: { Line } } </script> <template> <!-- Page Heading --> <h1 style = "text-align:center">Graphiques</h1> <Line id="my-chart-id" :options="chartOptions" :data="chartData" /> </template>
解决方案
错误原因
你错误地将vue-chartjs的Line组件传入ChartJS.register()方法中。Line是Vue组件,不是Chart.js的内置模块/元素,ChartJS无法识别并注册它,因此抛出"class does not have id"错误。此外,Line组件需要Chart.js的LineElement模块,你之前导入的BarElement仅适用于Bar组件。
修改后的代码
<script type="module"> import { Line } from 'vue-chartjs' // 导入Line组件需要的LineElement,移除无用的BarElement import { Chart as ChartJS, Title, Tooltip, Legend, LineElement, PointElement, CategoryScale, LinearScale } from 'chart.js' // 仅注册ChartJS所需的核心模块,移除Vue组件Line ChartJS.register(Title, Tooltip, Legend, LineElement, CategoryScale, LinearScale, PointElement) export default { data() { return { chartData: { labels: ['January', 'February', 'March'], datasets: [{ label:"Ventes", backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [40, 20, 12] }] }, chartOptions: { responsive: true } } }, components: { Line // 在Vue组件中正常注册Line即可 } } </script> <template> <h1 style="text-align:center">Graphiques</h1> <Line id="my-chart-id" :options="chartOptions" :data="chartData" /> </template>
关键修改点
- 从
ChartJS.register()中移除Line参数,避免将Vue组件当作ChartJS模块注册 - 导入
LineElement替换BarElement,满足Line组件的渲染需求 - 保留Vue组件中
components: { Line }的注册,这才是正确使用vue-chartjs组件的方式
内容的提问来源于stack exchange,提问作者Jean François Manatane
相关产品推荐
相关产品推荐

