ekjcfn3902039
ekjcfn3902039

Reputation: 1839

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 '';
        }
      }
    }
  }
});

Upvotes: 0

Views: 528

Answers (2)

Husam Elbashir
Husam Elbashir

Reputation: 7177

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

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Try to use an arrow function and define chartOptions as a computed property :

computed:{
  chartOptions(){
    return {
      tooltips: {
         callbacks: {
        label: (tooltipItem, data)=> {
            console.log(this.test);
            return '';
        }
      }
    }
  }
}

}

Upvotes: 1

Related Questions