Update value in multidimensional array in Vue

后端 未结 2 973
鱼传尺愫
鱼传尺愫 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:10

    One method that works:

    selectCell (row, col) {
      //make a copy of the row
      const newRow = this.grid[row].slice(0)
      // update the value
      newRow[col] = true
      // update it in the grid
      this.$set(this.grid, row, newRow)
    },
    

    Here is an 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 (let i = 0; i <= 2; i++) {
            this.grid[i] = []
            for (let j = 0; j <= 2; j++) {
              this.grid[i][j] = false
            }
          }
        },
        selectCell(row, col) {
          const newRow = this.grid[row].slice(0)
          newRow[col] = true
          this.$set(this.grid, row, newRow)
        },
        cellSelected(row, col) {
          return (this.grid[row][col] === true)
        }
      }
    })
    .selected {
      background-color: green;
    }
    
    
    {{rowKey+1}} {{col}}

    If I think of something better I'll update later.

提交回复
热议问题