Mah*_*dam 7 javascript arrays multidimensional-array vue.js
我从 Vue 文档的警告部分了解到,以下列方式更新数组中的值是行不通的:
this.arr[idx] = newVal
Run Code Online (Sandbox Code Playgroud)
那个应该使用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>
Run Code Online (Sandbox Code Playgroud)
这是 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)
}
}
Run Code Online (Sandbox Code Playgroud)
所以我试图向在我的方法中提供true的给定row col位置单击的单元格添加一个值selectCell。但是,我的网格中的数据并未更新以反映新增的价值。如何在 Vue 中更新多维数组中的值?
一种有效的方法:
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)
},
Run Code Online (Sandbox Code Playgroud)
这是一个例子。
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)
},
Run Code Online (Sandbox Code Playgroud)
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)
}
}
})Run Code Online (Sandbox Code Playgroud)
.selected {
background-color: green;
}Run Code Online (Sandbox Code Playgroud)
如果我想到更好的东西,我会稍后更新。