import Chart from "chart.js"
let AnalyticsChart = {
buildChart() {
let ctx = document.getElementById("analyticsChart");
let labels = ["sent", "delivered", "undelivered", "clicks"];
let total_sent = parseInt(document.getElementById("total-sent").dataset.totalSent);
let delivered = parseInt(document.getElementById("deilvered-count").dataset.deliveredCount);
let undelivered = parseInt(document.getElementById("undelivered-count").dataset.undeliveredCount);
let clicks = parseInt(document.getElementById("total-clicks").dataset.totalClicks);
let counts = [total_sent, delivered, undelivered, clicks]
let chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: counts,
backgroundColor: [
'rgba(54, 162, 235, 0.5)',
'rgba(255, 206, 86, 0.5)',
'rgba(255, 99, 132, 0.5)',
'rgba(75, 192, 192, 0.5)'
]
}]
},
options: {
}
});
},
update(){
}
}
export default AnalyticsChart
在此代码中,我想添加更新功能以更新图表。 我想通过图表变量来更新函数,该怎么做?
像这样
update(chart) {
let total_sent = parseInt(document.getElementById("total-sent").dataset.totalSent);
let delivered = parseInt(document.getElementById("deilvered-count").dataset.deliveredCount);
let undelivered = parseInt(document.getElementById("undelivered-count").dataset.undeliveredCount);
let clicks = parseInt(document.getElementById("total-clicks").dataset.totalClicks);
let counts = [total_sent, delivered, undelivered, clicks]
chart.data.datasets.forEach((dataset) => {
dataset.data.push(counts) # How can I put individual counts value?
});
chart.update();
}
我的问题 1.如何在buildChart()中传递图表变量以将函数更新为参数。 2.如何将单个counts元素放入dataset.data.push(counts)?
答案 0 :(得分:0)
我对您实施工具的方式不熟悉。
但是它看起来像Java,因此您需要成员变量,并使用每个函数中的this
来访问它们。
let AnalyticsChart = {
chart: null,
buildChart() {
/** omit **/
this.chart = new Chart(ctx, {
~
update() {
/** omit **/
this.chart.update();
很抱歉,我对这个问题不太了解。
您是否要推送数据而不是更新?如果是这样,您不能仅准备值。 (我的意思是,您需要标签,背景...)
如果您只想更新图表,那简直就是小菜一碟
this.chart.data.datasets.forEach((dataset) => {
dataset.data = counts;
});
请记住,您只有一个数据集。 如果数据集不是动态的,那么我认为就不需要循环。
this.chart.data.datasets[0].data = counts;