在 Vuejs 中使用 Reduce 计算 2D 数组



在 Vue 中,我在 2d 数组输入字段中插入一个值并每行计算它,但返回的总值只计算第一行,当我显示时,计算值都是一样的。

如何计算输入的值,以便该值将按行计算它,而不仅仅是第一个值?

这就是我得到的: 值的示例图像

小提琴:小提琴

姓名 |值1 |值 2 |总 名称1 |  1 |  1 |2 名称2 |  2 |  3 |2 名称3 |       |       |2

脚本

data() {
return {
form: new Form({
labStudentScores: [],
})
};
},
computed: {
studentTotalScore: function() {
return this.form.labStudentScores.reduce(
(acc, item) => acc + parseInt(item.value),
0
);
},
methods: {
addScore: function() {
this.form.labStudentScores.push({ value: [] });
}
}

模板

<button type="button" @click="addScore">score(+)</button>
//classlists is comming from http request
<tr v-for="(classlist,index) in classlists" :key="'lab'+ classlist.id">
<td>{{index +1}}</td>
<td>
{{classlist.student}}
</td>
<td v-for="(labStudentScore,i) in form.labStudentScores" :key="i">
<input v-model="labStudentScore.value[index]"  />
</td>
<td>{{studentTotalScore}}</td>
</tr>

您的计算变量实际上只是一个数字studentTotalScore。由于您希望每行都有一个数字,因此此计算值应为数组studentTotalScores。每一行都应有自己的索引。

this.form.labStudentScores[index].push(value);

在您的模板中,您还应该引用正确的行进行计算。

{{studentTotalScore[index]}}

当然,您的计算函数也应该只计算相关行的值。

最新更新