[Vuejs]-How to call a vue method from inside the xAxis.labels.formatter() highcharts object

0👍

This won’t work, returned value from a formatter function is treated as a string.

As a solution, you can store a label’s value in a data-* attribute and add change event after the chart is created.

export default {
  methods: {
    test(value) {
      console.log(value); 
    }
  },
  data() {
    const context = this;
    return {
      chartOptions: {
        chart: {
          events: {
            load: function() {
              const labelGroup = this.xAxis[0].labelGroup;
              const checkboxes = labelGroup.div.getElementsByTagName('input');
              
              for (const checkbox of checkboxes) {
                checkbox.addEventListener('change', function(e){
                  context.test(this.dataset.value);
                })
              }
            }
          }
        },
        xAxis: {
          showEmpty: false,
          title: null,
          type: 'category', 
          labels: {
            useHTML: true,
            formatter() {
              return `<input type='checkbox' data-value=${this.value}> ${this.value}`;
            }
          }
        }
      }
    };
  }
};

Live demo: https://codesandbox.io/s/highcharts-vue-demo-fork-j4ty16?file=/src/components/Chart.vue

Leave a comment