简体   繁体   中英

chart.js break line in a label with a tooltip callback

Working with chart.js in a vue.js component I was using a nested array to break line in my longs labels. Since I use a tooltips callback to add a % at the end of the labels they are not breaking line anymore.

Vue.component('ethique-chart', {
  extends: VueChartJs.Doughnut,
  mounted () {
    this.renderChart({
      labels: [['Lutte contre la corruption', 'active ou passive'], ['Actions en faveur de la responsabilité', 'sociétale chez les fournisseurs'] ],
      datasets: [
        {
          
          backgroundColor: [ '#0075AA', '#258BB7'],
          data: [90, 7]
        }
      ]
    }, 
    
    {responsive: true, maintainAspectRatio: false,legend: { display: false}, 
     animation: {
            duration: 3000, easing : 'easeInOutQuad'
        }, tooltips: { backgroundColor: 'rgba(231, 30, 116, .87)',
  callbacks: {
    label: function(tooltipItem, data) {
      return data['labels'][tooltipItem['index']] + ': ' + data['datasets'][0]['data'][tooltipItem['index']] + '%';
    }
  }
}
})
  }
  
})

You must make sure, the label callback function returns an array to make it work as expected. It could be written as follows:

callbacks: {
  label: function(tooltipItem, data) {
    let i = tooltipItem['index'];
    let label = data['labels'][i];
    return label.slice(0, -1).concat(label.slice(-1) + ': ' + data['datasets'][0]['data'][i] + '%');
  }
}

Please take a look at below runnable code to see how it works. This is plain JavaScript but the label callback function will look the same with Vue.js.

 new Chart('chart', { type: 'doughnut', data: { labels: [ ['Lutte contre la corruption', 'active ou passive'], ['Actions en faveur de la responsabilité', 'sociétale chez les fournisseurs'] ], datasets: [{ backgroundColor: ['#0075AA', '#258BB7'], data: [90, 7] }] }, options: { responsive: true, maintainAspectRatio: false, legend: { display: false }, animation: { duration: 3000, easing: 'easeInOutQuad' }, tooltips: { backgroundColor: 'rgba(231, 30, 116, .87)', callbacks: { label: function(tooltipItem, data) { let i = tooltipItem['index']; let label = data['labels'][i]; return label.slice(0, -1).concat(label.slice(-1) + ': ' + data['datasets'][0]['data'][i] + '%'); } } } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="chart"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM