[Chartjs]-"this" doesn't work in click event handler

4๐Ÿ‘

โœ…

You need to put the handler into your methods object and then reference it from the chart options handler:

data() {
  return {
    my_data: [],
    options: {
      onClick: this.ClickHandler,
    }
  };
},
methods: {
  ClickHandler: function(event, points) {
    // Here is how to access the chart
    const c = this._data._chart;
    const datapoint = c.getElementAtEvent(event)[0];
    const indexBar = datapoint._index;
    const indexSegment = datapoint._datasetIndex;
    // Do whatever with this.my_data, indexBar, and indexSegment
  }
}

The chart is accessible to the component through this._data._chart.

2๐Ÿ‘

Create a closure variable

data() {
    const vm = this;
    return {
      my_data: [],
      options: {
        onClick: function(event, args) {
           this.chartjs.something;
           vm.my_data[]
        }
      }
}

Leave a comment