我从Vue的文档的警告部明白,在以下面的方式的阵列来更新值将不起作用:更新值中的Vue
this.arr[idx] = newVal
并且一个应当使用splice()
。我正在使用二维数组来存储网格数据,并且当单击网格中的单元格时,我很难更新值。
这里是我的模板:
<tr
v-for="(row, rowKey, index) in grid"
:key="rowKey">
<th
class="row-col-label"
>{{rowKey+1}}</th>
<td
v-for="(col, colKey, index) in row"
:key="colKey"
@click="selectCell(rowKey, colKey)"
:class="{'selected' : cellSelected(rowKey, colKey)}"
>
{{col}}
</td>
</tr>
这里是为Vue的组件的相关代码:
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) {
this.isSelected = true
console.log(`row ${row} col ${col}`)
this.grid[row].splice(col, 1, true)
for (let i = 0; i <= 2; i++) {
for (let j = 0; j <= 2; j++) {
console.log(this.grid[i][j])
}
}
},
cellSelected (row, col) {
return (this.grid[row][col] === true)
}
}
所以我试图将一个true
值添加到是点击位于小区在我的selectCell
方法中提供的给定的row
col
位置。但是,我的网格中的数据未更新以反映新增值。我如何更新Vue中多维数组中的值?
谢谢!我最终做的是为了在设置新值之后更新整个网格并且它似乎正在工作而this.grid = this.grid.map(el => el.splice());但是,您的解决方案看起来好多了。 –