我知道我们可以使用以下代码加载图表工具提示的信息:
window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return tooltipItems.yLabel + ' €';
}
}
},
}
});
问题是,在我的情况下,我需要调用一个函数并异步返回值;可能会显示一个微调器,直到响应准备好。我怎样才能做到这一点?
最佳答案
您可以调用 chart.js 更新()而是异步方法。如果标签应该取决于用户悬停的数据点,您可能还需要使用递归。
window.myLine = new Chart(chart, {
type: 'line',
data: lineChartData,
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: asyncTooltipLabel
}
},
}
});
function asyncTooltipLabel(tooltipItems, data) {
// some asynchronous function call
setTimeout(function() {
// when asyncronous result comes
const result = (tooltipItems[0].index * 2) + ' €';
const newTooltipConfig = {
enabled: true,
mode: 'single',
callbacks: {
label: function(newTooltipItems, newData) {
if (newTooltipItems[0].index === tooltipItems[0].index && newTooltipItems[0].datasetIndex === tooltipItems[0].datasetIndex) return result;
else asyncTooltipLabel(newTooltipItems, newData);
}
}
}
// apply new tooltip config
window.myLine.options.tooltips = newTooltipConfig;
window.myLine.update();
}, 2000);
}
关于javascript - 异步加载 Chart.js 工具提示信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59312407/