Search code examples
javascriptvue.jsvuejs2chart.jsvue-chartjs

How to emit an event with vue-chartjs?


I use vue js and I display a graph with chartjs. When I click on the graph I want emit an event for get data in parent component. My onClick function works but not the event. Do you have an idea of my problem ? Component Line2.vue

<script>
import { mixins, Line } from "vue-chartjs";
const { reactiveProp } = mixins;
export default {
  extends: Line, 
  mixins: [reactiveProp],
  props: ["options"],
  mounted() {
    const self = this;
    console.log(self);
    this.options.onClick = function (e, tooltipItems) {
      console.log(tooltipItems[0].__ob__); //.logged
      self.$emit("sendIndex", tooltipItems[0]._index);
    };
    this.renderChart(this.chartData, this.options);
  },
};
</script>
<style scoped></style>

My main component

...
    <h1 v-on:sendIndex="getIndexCoord($event)">{{ indexCoord }}</h1>
...
methods: {
    getIndexCoord: function (e) {
      console.log("rrr", e); //Not logged
      this.indexCoord = e;
    },
}

Regards


Solution

  • 1.first you create EventBus.js file import Vue from 'vue';

    export const EventBus = new Vue();
    

    2.In your char.js file code like below

    import { EventBus } from "../EventBus.js";
    import { mixins, Line } from "vue-chartjs";
    const { reactiveProp } = mixins;
    export default {
      extends: Line, 
      mixins: [reactiveProp],
      props: ["options"],
      mounted() {
        const self = this;
        console.log(self);
        this.options.onClick = function (e, tooltipItems) {
          console.log(tooltipItems[0].__ob__); //.logged
          EventBus.$emit("sendIndex", tooltipItems[0]._index);
        };
        this.renderChart(this.chartData, this.options);
      },
    };
    
    1. where you want to access your data in that file like below

      import { EventBus } from "../EventBus.js";
      mounted() {
      
         EventBus.$on('sendIndex', data => {
            console.log(data)
           });
      
      },