Update value in multidimensional array in Vue

后端 未结 2 974
鱼传尺愫
鱼传尺愫 2021-01-12 18:50

I understand from the caveats portion of the Vue docs that updating a value in an array in the following manner will not work:

  this.arr[idx] = newVal
         


        
2条回答
  •  醉酒成梦
    2021-01-12 19:02

    The difficulty is that you're building the array in a way that Vue does not make its rows reactive. You could build the array and then assign it to the data item as a whole so that Vue would make it reactive, or you can build the array (at last the rows) using push, which will make them reactive. Then you can modify individual elements using splice. Modifying Bert's example:

    console.clear()
    
    
    new Vue({
      el: "#app",
      created() {
        this.initColHead()
        this.createSpreadSheet()
      },
      data() {
        return {
          selected: '',
          grid: [],
          colHead: [' '],
          isSelected: false
        }
      },
      methods: {
        initColHead() {
          this.colHead.push(...'ABC'.split(''))
        },
        createSpreadSheet() {
          for (var i = 0; i <= 2; i++) {
            this.grid.push([]);
            for (var j = 0; j <= 2; j++) {
              this.grid[i].push(false);
            }
          }
        },
        selectCell(row, col) {
          this.grid[row].splice(col, 1, true);
        },
        cellSelected(row, col) {
          return (this.grid[row][col] === true)
        }
      }
    })
    .selected {
      background-color: green;
    }
    
    
    {{rowKey+1}} {{col}}

提交回复
热议问题