vue实现表格编辑
Vue 实现表格编辑的方法
双向绑定实现基础编辑
使用 v-model 绑定表格单元格数据,适合简单场景:
<template>
<table>
<tr v-for="(row, index) in tableData" :key="index">
<td v-for="(col, colIndex) in row" :key="colIndex">
<input v-model="tableData[index][colIndex]" />
</td>
</tr>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
['数据1', '数据2'],
['数据3', '数据4']
]
}
}
}
</script>
条件渲染编辑状态
通过 isEditing 状态控制显示输入框或文本:

<template>
<td @click="startEdit(row, col)">
<input v-if="row.isEditing" v-model="row[col]" @blur="stopEdit(row)" />
<span v-else>{{ row[col] }}</span>
</td>
</template>
<script>
export default {
methods: {
startEdit(row, col) {
row.isEditing = true
this.$nextTick(() => {
this.$refs[`input_${row.id}_${col}`][0].focus()
})
},
stopEdit(row) {
row.isEditing = false
}
}
}
</script>
使用第三方组件库
Element UI 的表格编辑方案:

<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名">
<template #default="{row}">
<el-input v-if="row.edit" v-model="row.name" />
<span v-else>{{ row.name }}</span>
</template>
</el-table-column>
</el-table>
</template>
完整可编辑表格示例
<template>
<div>
<button @click="addRow">新增行</button>
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(col, colIndex) in row" :key="colIndex">
<input v-if="editing[rowIndex]" v-model="tableData[rowIndex][colIndex]" />
<span v-else>{{ col }}</span>
</td>
<td>
<button @click="toggleEdit(rowIndex)">
{{ editing[rowIndex] ? '保存' : '编辑' }}
</button>
<button @click="deleteRow(rowIndex)">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职业'],
tableData: [
['张三', 25, '工程师'],
['李四', 30, '设计师']
],
editing: []
}
},
methods: {
toggleEdit(index) {
this.$set(this.editing, index, !this.editing[index])
},
addRow() {
this.tableData.push(['', '', ''])
this.editing.push(true)
},
deleteRow(index) {
this.tableData.splice(index, 1)
this.editing.splice(index, 1)
}
}
}
</script>
性能优化建议
对于大数据量表格,使用虚拟滚动技术:
// 安装 vue-virtual-scroller
import { RecycleScroller } from 'vue-virtual-scroller'
// 组件中使用
<RecycleScroller
class="scroller"
:items="largeTableData"
:item-size="50"
key-field="id"
v-slot="{ item }">
<!-- 渲染单行内容 -->
</RecycleScroller>
数据验证处理
编辑时添加数据验证:
methods: {
validateRow(row) {
return row.every(col => {
if (col === 'age') return !isNaN(col)
return col.trim() !== ''
})
},
saveEdit(index) {
if (this.validateRow(this.tableData[index])) {
this.editing[index] = false
} else {
alert('数据校验失败')
}
}
}






