如何从xAxis.labels.formatter()highcharts对象内部调用vue方法

o2gm4chl  于 2022-11-10  发布在  Highcharts
关注(0)|答案(1)|浏览(208)

因此,我尝试实现的是,在xAxis中的值之前应该有一个复选框,当通过单击复选框来更改复选框时,它应该调用我的test() vue方法。现在,当调用buildChart()方法时,它调用的是test()

buildChart() {
      const context = this;
      return {
        chart: {
          height: 500,
          type: 'columnrange',
          inverted: true,
          spacingLeft: 10,
          spacingRight: 10,
        },
        xAxis: {
        showEmpty: false,
        title: null,
        type: 'category',
          labels: {
            useHTML: true,
            formatter() {
              // This is where i am rendering the checkbox, would like it to trigger my vue function which is within the current vue context.
              return `<input type='checkbox' onchange='${context.test(this.value)}'> ${this.value}`;
            },
          },
        },
     };
}
test(value) {
console.log(value);
}
pbgvytdp

pbgvytdp1#

这是行不通的,从formatter函数返回的值被视为字符串。
作为解决方案,您可以将标签的值存储在data-*属性中,并在创建图表后添加change事件。

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}`;
            }
          }
        }
      }
    };
  }
};

现场演示:https://codesandbox.io/s/highcharts-vue-demo-fork-j4ty16?file=/src/components/Chart.vue

相关问题