Search code examples
javascriptvue.jschart.js

vue-chartjs register plugin to only one chart component


I have a chart as its own Vue component (Vue 3 and using composition API), and I would like to add in the datalabels plugin to this chart only.

If I register the plugin outside the chart data or options all charts in the application have labels:

<script setup>

import {
    Chart as ChartJS,
    Title,
    Tooltip,
    Legend,
    BarElement,
    CategoryScale,
    LinearScale,
} from 'chart.js'
import ChartJSPluginDatalabels from 'chartjs-plugin-datalabels'
import { Bar } from 'vue-chartjs'

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

</script>

I tried adding the plugin into the data, but nothing happens:

const data = {
    plugins:[ChartJSPluginDatalabels],
    labels: ['A', 'B','C'],
    datasets: [
        {
            data: data1,
            label: 'Data 1'
        },
        {
            data: data2,
            label: "Data 2"
        }
    ]
}

I've also tried adding into the options. If I instead use plugins:[ChartJS.register(ChartJSPluginDatalabels)] this also applies it to all charts within the application.

The template of the component is simply:

<template>
    <Bar :data="data" :options="options" />
</template>

Solution

  • For other guys like me that landed here from google...

    Leave only import in script part

    <script setup>
    import ChartJSPluginDatalabels from 'chartjs-plugin-datalabels'
    ...
    

    Add plugins to needed component instead:

    <Bar :data="data" :options="options" :plugins="[ChartJSPluginDatalabels]" />