Search code examples
javascriptvue.jschart.jsvuejs3vue-chartjs

vue 3 chart js chart is undefined in click event


I am currently trying to upgrade my site to vue 3 from vue 2 and as part of this, I have had to updgrade vue-chartjs from version 4 to 5 and it seems to have broken my click event.

Previously I had the chart on my page like so:

<bar v-if="loaded"
   ref="chart"
   :data="chartData"
   :options="chartOptions">
</bar>

import { Bar } from 'vue-chartjs';

And I could use the following in my options click event:

onClick: event => {
    const chart = this.$refs.chart._data._chart;
    const activeElement = chart.getElementAtEvent(event)[0];
}

Since I have upgraded, _data is now undefined, so I tried to get the chart object by doing this.$refs.chart.chart, but now I get the following error:

chart.getElementAtEvent is not a function

Does anyone know how to get the chart so I can call the getElementAtEvent - or if this is still the correct function to get the label from the bar that is clicked on?

Current code stackblitz


Solution

  • As described in the V3 migration guide

    getElementAtEvent is replaced with chart.getElementsAtEventForMode(e, 'nearest', { intersect: true }, false)

    working sandbox link: https://stackblitz.com/edit/github-ofrpcb-srknqa?file=src%2FApp.vue