Search code examples
javascriptvue.jsvuejs2vue-componentvue-chartjs

Reference prop from callback


I am trying to reference the vue props inside a callback in vue-chartjs but it can't resolve 'this' and I get an 'undefined' error in the console log. What is the correct way to reference the prop?

props: {
  test: {
    type: String,
    required: true,
  },
}
data: () => ({
  chartOptions: {
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
            console.log(this.test);
            return '';
        }
      }
    }
  }
});

Solution

  • If you want to use this in your data you have to use a normal function so that the this keyword could be correctly bound to the Vue instance ..

    
    export default {
        props: {
            test: {
                type: String,
                required: true,
            },
        },
        data() {
            const vm = this
            return {
                chartOptions: {
                    tooltips: {
                        callbacks: {
                            label: function(tooltipItem, data) {
                                console.log(vm.test);
                                return '';
                            }
                        }
                    }
                }
            }
        }
    }