Chart.js 3.9 and Vue: Unable to handle onClick event

Usually, StackOverflow is my last resort cause I don’t enjoy being annoyed and I assume neither do you, but I’m desperate.

I want to capture a click on a graph Bar but I don’t see a trace in the logs that the click event has been thrown. I was using Chart.js 2.8.9 but upgraded to 3.9 thinking it could be a bug.

This is my vue file where I load the Graphics:

<template>
    <div>
        <h4>Gráficas de miembros activos</h4>
        <div>
            <!-- Pasamos chartData y el evento bar-clicked -->
            <bar-chart :chart-data="datos" :opciones="opciones" @bar-clicked="handleBarClick" />
        </div>
    </div>
</template>

<script>
    import BarChart from "../components/BarChart";
    import api from "@/api";

    export default {
        name: "Graficas",
        components: { BarChart },
        data() {
            return {
                datos: {},   // Datos del gráfico
                opciones: {} // Opciones del gráfico
            };
        },
        methods: {
            graficar: function (sector_id) {
                api.graficas(sector_id).then((r) => {
                    this.datos = r.data; 

                    // Configuración de colores y bordes de las barras
                    this.datos.datasets[0].backgroundColor = [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(255, 159, 64, 0.2)',
                        'rgba(255, 205, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(153, 102, 255, 0.2)',
                        'rgba(201, 203, 207, 0.2)'
                    ];
                    this.datos.datasets[0].borderColor = [
                        'rgb(255, 99, 132)',
                        'rgb(255, 159, 64)',
                        'rgb(255, 205, 86)',
                        'rgb(75, 192, 192)',
                        'rgb(54, 162, 235)',
                        'rgb(153, 102, 255)',
                        'rgb(201, 203, 207)'
                    ];
                    this.datos.datasets[0].borderWidth = 1;

                    // Opciones del gráfico
                    this.opciones = {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        },
                        responsive: true,
                        maintainAspectRatio: false,
                        height: 300
                    };
                })
                .catch(error => {
                    console.log(error);
                });
            },
            handleBarClick({ data, dataIndex, datasetIndex }) {
                // Este método captura el evento bar-clicked y muestra la información del clic
                console.log(`Clicked bar at index ${dataIndex} in dataset ${datasetIndex}:`, data);
            }
        },
        mounted() {
            const sector_id = this.$route.params.id ?? 0;
            this.graficar(sector_id);
        },
    };
</script>

And this is the class we created to extend Chart.js:

import { Chart, registerables } from 'chart.js';

Chart.register(...registerables); // Registro de todos los componentes necesarios

export default {
  props: {
    chartData: {
      type: Object,
      required: true
    },
    opciones: {
      type: Object,
      default: () => ({})
    }
  },
  mounted() {
    const canvas = this.$refs.canvas;

    // Verificamos que el canvas existe y tiene contexto 2D
    if (!canvas || !canvas.getContext) {
      console.error("No se pudo obtener el contexto del canvas.");
      return;
    }

    const ctx = canvas.getContext('2d');

    // Configuración de las opciones de la gráfica
    this.opciones.scales = {
      y: {
        beginAtZero: true
      }
    };
    this.opciones.plugins = {
      datalabels: {
        color: "black",
        textAlign: "center",
        anchor: 'start',
        font: {
          weight: "bold",
          size: 14,
        }
      }
    };
    this.opciones.responsive = true;
    this.opciones.maintainAspectRatio = false;
    this.opciones.hover = {
      mode: 'nearest',
      intersect: true
    };
    this.opciones.interaction = {
      mode: 'index',
      intersect: false
    };

    // Establecemos una altura fija para el canvas a través de CSS
    canvas.style.height = '400px';
    canvas.style.width = '100%'; 

    // Instancia del gráfico
    this.chartInstance = new Chart(ctx, {
      type: 'bar',
      data: this.chartData,
      options: {
        ...this.opciones,
        onClick: (event, elements) => {
          console.log('onClick event triggered');
          if (elements.length > 0) {
            const element = elements[0];
            const dataIndex = element.index;
            const datasetIndex = element.datasetIndex;
            console.log('Data point clicked:', dataIndex, datasetIndex);
            const data = this.chartData.datasets[datasetIndex].data[dataIndex];
            this.$emit('bar-clicked', { data, dataIndex, datasetIndex });
          } else {
            console.log('No elements clicked.');
          }
        }
      }
    });

  },
  watch: {
    chartData(newData) {
      if (this.chartInstance) {
        this.chartInstance.data = newData;
        this.chartInstance.update();
      }
    },
    opciones(newOptions) {
      if (this.chartInstance) {
        this.chartInstance.options = newOptions;
        this.chartInstance.update();
      }
    }
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.destroy();
    }
  },
  render(h) {
    return h('canvas', { ref: 'canvas' });
  }
};

The JSON returned by the backend is simple, so the error shouldn’t be there:

    {
  "datasets": [
    {
      "data": [
        15,
        5,
        0,
        0,
        0
      ],
      "label": "Sector San Felipe De Jesus"
    }
  ],
  "labels": [
    "Matrimonios",
    "MaRes",
    "Ju00f3venes",
    "Adolescentes",
    "Asistentes Eclesiales"
  ]
}

The Graphic is shown but I don’t see a trace in the logs for the click. Any ideas?

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật