首页 > 解决方案 > 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

标签: vue.jsmultidimensional-arrayreduce

解决方案


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.


推荐阅读