【发布时间】:2016-10-13 06:56:43
【问题描述】:
我的表格中有一些可编辑的数据,其中包含要计算的行和列的总和。
因为我想要更简单的 html 代码,所以我使用 repeat.for 来构建表格的行。为了求和,我使用了一个函数,这是迄今为止我想出的最好的方法。
不幸的是,当我编辑这些值时,总和不会以这种方式更新。 Getter 函数可以通过计算得到,但它们不能接受参数。
我知道我可以写类似 ${$parent.data[y]['Q1'] + $parent.data[y]['Q2'] + ...} 的东西,但这会变得很长,什么是'此示例中的 Q1' 将是现实生活中的动态。 对于列的总和,我将有 15 行需要求和 - 我宁愿不必为此在 html 中编写求和语句。
我正在查看 observatorlocator,但不知道如何将其用于我的案例。我认为这是一个相当简单的场景,所以我希望在 Aurelia 中有一个很好的解决方案。
test.js
export class Test {
data = {
"2015": { "Q1": 7318, "Q2": 6215, "Q3": null, "Q4": 3515 },
"2016": { "Q1": 1234, "Q2": 2345, "Q3": 3345, "Q4": 3000 },
"2017": { "Q1": 4233, "Q2": 999, "Q3": 1234, "Q4": 3268 },
"2018": { "Q1": 7375, "Q2": 4415, "Q3": 8415, "Q4": 1005 },
"2019": { "Q1": null, "Q2": 5698, "Q3": 1254, "Q4": 6635 }
};
years() {
return Object.keys(this.data);
}
sumY(y) {
var sum = 0;
Object.values(this.data[y])
.forEach(function(item){
sum += item;
});
return sum;
}
sumQ(q) {
var sum = 0;
Object.values(this.data)
.forEach(function(item) {
sum += item[q];
});
return sum;
}
}
test.html
<template>
<table>
<thead>
<tr>
<td>Year</td>
<td>Q1</td>
<td>Q2</td>
<td>Q3</td>
<td>Q4</td>
<td>Sum</td>
</tr>
</thead>
<tbody>
<tr repeat.for="y of years()">
<td>${y}</td>
<td><input type="text" value.bind="$parent.data[y]['Q1']" /></td>
<td><input type="text" value.bind="$parent.data[y]['Q2']" /></td>
<td><input type="text" value.bind="$parent.data[y]['Q3']" /></td>
<td><input type="text" value.bind="$parent.data[y]['Q4']" /></td>
<td class="ansatz">${$parent.sumY(y)}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>${sumQ("Q1")}</td>
<td>${sumQ("Q2")}</td>
<td>${sumQ("Q3")}</td>
<td>${sumQ("Q4")}</td>
</tr>
</tfoot>
</table>
</template>
【问题讨论】:
标签: javascript aurelia