ChartJS 3.7.1 工具提示回调,获取下一个索引的标签值

ChartJS 3.7.1 tooltip callback, get label value for the next index

我目前正在从 2.9.3 迁移到 3.7.1,我在从选项对象迁移回调函数时遇到了问题。

以前的位置:options.tooltips.callbacks.title
迁移位置:options.plugins.tooltip.callbacks.title

前函数(简化):

function (tooltipItems, data) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = data.labels[tooltipItem.index];
    var nextLabel = data.labels[tooltipItem.index +1];
    return currentLabel + ' - ' + nextLabel;
}

迁移函数:

function (tooltipItems) {
    var tooltipItem = tooltipItems[0];
    var currentLabel = tooltipItem.label;
    var nextLabel = ? // how to get nextLabel?
    return currentLabel + ' - ' + nextLabel;
}

tooltipItem.dataset 有一个标签数组,但当我 console.log(tooltipItems)

时它显示为空

您可以访问图表对象并拥有数据索引,因此您可以像这样从标签数组中获取正确的标签:

title: (items) => {
  const item = items[0];
  const {
    chart
  } = item;
  const nextLabel = chart.data.labels[item.dataIndex + 1] || '';
  return `${item.label}, next label: ${nextLabel}`;
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          title: (items) => {
            const item = items[0];
            const {
              chart
            } = item;
            const nextLabel = chart.data.labels[item.dataIndex + 1] || '';
            return `${item.label}, next label: ${nextLabel}`;
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>