vue.js - VUE:使用多个输入计算二维数组
问题描述
在 Vue 中,我在 2d 数组输入字段中插入一个值并按行计算它,但是返回的总值只计算第一行,当我显示时,计算的值都是一样的。
我如何计算输入的值,以便该值将按行计算,而不仅仅是第一个值?
<button @click="addFind">add</button>
<tr v-for="(classlist,index) in classlists" :key="'lab'+ classlist.id">
<td>{{index +1}}</td>
<td>{{classlist.student}}</td>
<td v-for="(lab, i) in labs">
<input v-model="lab.value[index]" />
</td>
</tr>
labs: [],
classlists: [
{ "student": "S1","id": 1 },
{ "student": "S2","id": 2 },
{ "student": "S3","id": 3 },
{ "student": "S3","id": 4 },
],
},
methods: {
addFind: function () {
this.labs.push({ value: [] });
}
},
computed: {
studentTotalScores: function() {
return this.labStudentScores.reduce(
(acc, item) => acc + parseInt(item.value),
0
);
}
}
我需要的:
姓名 | 价值1 | 价值2 | 全部的 名称1 | 1 | 1 | 2 名称2 | 2 | 3 | 5 名称3 | | | 0
但是输出:jsfiddle
姓名 | 价值1 | 价值2 | 全部的 名称1 | 1 | 1 | 2 名称2 | 2 | 3 | 2 名称3 | | | 2
解决方案
A computed property can only have a single value, you can't calculate it 'per row'.
What you can do is have the value be an array, with one entry per row.
The data structure you're working with is a bit of a pain as the arrays are transposed relative to the table. Still, it can be done with a bit of fighting.
First, in the template you'd add a suitable <td>
to the end of the rows:
<tr v-for="(classlist, index) in classlists" :key="'lab' + classlist.id">
... other tds not shown ...
<td>
{{ studentTotalScores[index] }}
</td>
</tr>
Then studentTotalScores
would be:
studentTotalScores: function() {
return this.classlists.map((c, index) => {
return this.labs.reduce((acc, item) => {
const value = parseInt(item.value[index], 10) || 0
return acc + value
}, 0)
})
}
I've added a base of 10
to parseInt
to ensure consistent parsing, as well as || 0
so that NaN
will be treated as 0
.
推荐阅读
- latex - LaTeX - 水平线上方不需要的空间
- node.js - 在 express.js 中间件函数中无法接收错误
- visual-studio - 使用 Nuget 部署一个自包含的 React 应用程序
- java - 如何找出 JSONDeserializer 的启动和完成时间?
- r - rlang::eval_tidy 调用自定义数据对象
- ansible - 如何处理带有条件的_items
- connection - Tizen 错误 - 无法连接到远程目标 [ip]
- css - 在 angular6 上渲染 UI 时出现 CSSStyleDeclaration 错误
- python - 循环以将值减小为十的幂
- cloud - 服务到服务的通信:API Gateway vs. Service Mesh