vue实现网格填入
Vue 实现网格填入
在 Vue 中实现网格填入功能,可以通过动态绑定数据和使用 v-for 指令来渲染网格内容。以下是一个完整的实现步骤:
创建 Vue 实例和数据
new Vue({
el: '#app',
data: {
gridData: [
['', '', ''],
['', '', ''],
['', '', '']
]
}
});
模板中使用 v-for 渲染网格
<div id="app">
<div class="grid">
<div v-for="(row, rowIndex) in gridData" :key="rowIndex" class="row">
<div v-for="(cell, colIndex) in row" :key="colIndex" class="cell">
<input v-model="gridData[rowIndex][colIndex]" />
</div>
</div>
</div>
</div>
添加样式
.grid {
display: flex;
flex-direction: column;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
.cell input {
width: 90%;
height: 90%;
text-align: center;
border: none;
outline: none;
}
动态调整网格大小
如果需要动态调整网格大小,可以添加方法:

methods: {
resizeGrid(rows, cols) {
this.gridData = Array(rows).fill().map(() => Array(cols).fill(''));
}
}
完整示例代码
<div id="app">
<div>
<button @click="resizeGrid(3, 3)">3x3</button>
<button @click="resizeGrid(4, 4)">4x4</button>
</div>
<div class="grid">
<div v-for="(row, rowIndex) in gridData" :key="rowIndex" class="row">
<div v-for="(cell, colIndex) in row" :key="colIndex" class="cell">
<input v-model="gridData[rowIndex][colIndex]" />
</div>
</div>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
gridData: [
['', '', ''],
['', '', ''],
['', '', '']
]
},
methods: {
resizeGrid(rows, cols) {
this.gridData = Array(rows).fill().map(() => Array(cols).fill(''));
}
}
});
</script>
<style>
.grid {
display: flex;
flex-direction: column;
}
.row {
display: flex;
}
.cell {
width: 50px;
height: 50px;
border: 1px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
.cell input {
width: 90%;
height: 90%;
text-align: center;
border: none;
outline: none;
}
</style>
通过以上代码,可以实现一个基本的网格填入功能,并支持动态调整网格大小。用户可以在每个单元格中输入内容,数据会自动同步到 Vue 实例的 gridData 中。





