vue实现网格填入
Vue 网格填入实现方法
使用 v-for 动态渲染网格
通过 Vue 的 v-for 指令可以快速生成网格结构,结合计算属性动态控制填入内容:
<template>
<div class="grid-container">
<div
v-for="(item, index) in gridItems"
:key="index"
class="grid-item"
@click="fillGrid(index)"
>
{{ item.value }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
gridItems: Array(9).fill().map((_, i) => ({ id: i, value: '' }))
}
},
methods: {
fillGrid(index) {
this.gridItems[index].value = 'X' // 可替换为实际填入逻辑
}
}
}
</script>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 10px;
}
.grid-item {
border: 1px solid #ddd;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
}
</style>
双向绑定实现表单填入
对于需要用户输入的网格,可以使用 v-model 实现双向绑定:

<template>
<div class="input-grid">
<div v-for="row in 5" :key="row" class="row">
<input
v-for="col in 5"
:key="col"
v-model="gridData[row-1][col-1]"
class="cell"
>
</div>
</div>
</template>
<script>
export default {
data() {
return {
gridData: Array(5).fill().map(() => Array(5).fill(''))
}
}
}
</script>
拖拽填入功能实现
结合 HTML5 拖放 API 实现更复杂的交互:

methods: {
handleDragStart(e, item) {
e.dataTransfer.setData('text/plain', item.id)
},
handleDrop(e, cellIndex) {
const itemId = e.dataTransfer.getData('text/plain')
this.gridItems[cellIndex].value = this.items.find(i => i.id === itemId).content
},
allowDrop(e) {
e.preventDefault()
}
}
使用第三方库
对于复杂场景,可以考虑以下库:
- Vue Draggable:实现可排序拖拽网格
- Vue Grid Layout:专业级响应式网格布局
- Vuetify Data Grid:提供完整的数据表格功能
性能优化建议
- 大数据量时使用虚拟滚动(vue-virtual-scroller)
- 复杂计算使用计算属性缓存结果
- 频繁更新的操作使用
requestAnimationFrame - 避免在模板中使用复杂表达式
响应式设计要点
通过 CSS Grid 的响应式特性适配不同屏幕:
@media (max-width: 768px) {
.grid-container {
grid-template-columns: repeat(2, 1fr);
}
}



