vue实现网格填入
Vue 实现网格填入
在 Vue 中实现网格填入功能,可以通过动态绑定数据和循环渲染网格来实现。以下是一个简单的实现方法:
创建 Vue 实例并定义数据
在 Vue 实例的 data 中定义一个二维数组来表示网格数据。每个单元格可以包含初始值或为空。
new Vue({
el: '#app',
data: {
grid: [
['', '', ''],
['', '', ''],
['', '', '']
]
}
});
渲染网格
使用 v-for 指令循环渲染网格的行和列。通过 v-model 绑定输入框的值到对应的网格单元格。

<div id="app">
<div v-for="(row, rowIndex) in grid" :key="rowIndex" class="grid-row">
<input
v-for="(cell, colIndex) in row"
:key="colIndex"
v-model="grid[rowIndex][colIndex]"
type="text"
class="grid-cell"
/>
</div>
</div>
添加样式
为网格添加简单的样式,使其看起来更整齐。
.grid-row {
display: flex;
}
.grid-cell {
width: 50px;
height: 50px;
margin: 2px;
text-align: center;
}
动态调整网格大小
如果需要动态调整网格大小,可以通过方法修改 grid 数据。

methods: {
resizeGrid(rows, cols) {
this.grid = Array(rows).fill().map(() => Array(cols).fill(''));
}
}
添加事件处理
可以为输入框添加事件处理,例如在输入完成后触发验证或其他逻辑。
<input
v-for="(cell, colIndex) in row"
:key="colIndex"
v-model="grid[rowIndex][colIndex]"
@blur="validateCell(rowIndex, colIndex)"
type="text"
class="grid-cell"
/>
methods: {
validateCell(row, col) {
if (this.grid[row][col] === 'invalid') {
alert('Invalid input!');
}
}
}
完整示例
以下是一个完整的 Vue 网格填入示例:
<div id="app">
<div v-for="(row, rowIndex) in grid" :key="rowIndex" class="grid-row">
<input
v-for="(cell, colIndex) in row"
:key="colIndex"
v-model="grid[rowIndex][colIndex]"
@blur="validateCell(rowIndex, colIndex)"
type="text"
class="grid-cell"
/>
</div>
<button @click="resizeGrid(4, 4)">Resize to 4x4</button>
</div>
<style>
.grid-row {
display: flex;
}
.grid-cell {
width: 50px;
height: 50px;
margin: 2px;
text-align: center;
}
</style>
<script>
new Vue({
el: '#app',
data: {
grid: [
['', '', ''],
['', '', ''],
['', '', '']
]
},
methods: {
resizeGrid(rows, cols) {
this.grid = Array(rows).fill().map(() => Array(cols).fill(''));
},
validateCell(row, col) {
if (this.grid[row][col] === 'invalid') {
alert('Invalid input!');
}
}
}
});
</script>
通过以上方法,可以在 Vue 中实现一个简单的网格填入功能,并支持动态调整大小和输入验证。





