有一些教程(例如 https://medium.com/geekculture/chart-js-in-nuxt-js-how-to-implement-c255a2657b02)展示了如何将 Chart.js 与早期版本集成Nuxt 3甚至Nuxt 2的版本。但它们由于各种原因不起作用。本教程例如 https://dev.to/anggakswr/chart-js-in-nuxt-js-4hjf 导致 500 错误:
Cannot read properties of undefined (reading 'component')
at ./plugins/charts.js:6:31
at async ViteNodeRunner.directRequest (./node_modules/vite-
node/dist/client.mjs:331:5)
此外,还有不同的方法:一个教程/示例使用“Nuxt 插件”方式,另一种使用“Nuxt 组件”方式...
我尝试了基于此处文档的插件方式:https://nuxt.com/docs/guide/directory-struct/plugins#vue-plugins:
// plugins/charts.js
import { Bar } from "vue-chartjs"
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(Bar)
})
但是一旦我运行
npm run dev
,我就会收到此警告:
[Vue warn]:插件必须是一个函数或具有“安装”功能的对象。
后来:
[Vue warn]: Failed to resolve component: BarChart
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.
at <Chart onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > >
这是一个代码和框: https://codesandbox.io/p/sandbox/gracious-lumiere-88bw4j
我需要做什么才能让 (vue-)chart.js 正常工作?
这是Nuxt 3中chartjs的基本示例。希望这对您有帮助。
安装chart.js
npm i vue-chartjs chart.js
有两种可能的选项可供您实施。
1。全局注册ChartJS
~/plugins/chartjs.ts
import { Chart, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'
export default defineNuxtPlugin(() => {
Chart.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)
})
组件使用示例。
<script lang="ts" setup>
import { Bar } from 'vue-chartjs'
const chartData = ref({
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: [40, 20, 12, 50, 10],
},
],
})
const chartOptions = ref({
responsive: true,
maintainAspectRatio: false,
})
</script>
<template>
<div>
<Bar
:data="chartData"
:options="chartOptions"
/>
</div>
</template>
2。手动注册ChatJS
<script lang="ts" setup>
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'
import { Bar } from 'vue-chartjs'
// Register
ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)
const chartData = ref({
labels: ['January', 'February', 'March', 'April', 'May'],
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: [40, 20, 12, 50, 10],
},
],
})
const chartOptions = ref({
responsive: true,
maintainAspectRatio: false,
})
</script>
<template>
<div>
<Bar
:data="chartData"
:options="chartOptions"
/>
</div>
</template>
<style scoped lang="css"></style>
两者的工作取决于您的需求。