vue实现表格的增
Vue 实现表格增删功能
在 Vue 中实现表格的增删功能需要结合数据绑定和事件处理。以下是具体实现方法:
基础表格结构
使用 v-for 指令渲染表格数据,并通过 v-model 实现双向绑定:

<template>
<div>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<button @click="deleteRow(index)">删除</button>
</td>
</tr>
</tbody>
</table>
<div>
<input v-model="newItem.name" placeholder="姓名">
<input v-model="newItem.age" placeholder="年龄">
<button @click="addRow">添加</button>
</div>
</div>
</template>
数据与逻辑处理
在 script 部分定义数据和操作方法:

<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 }
],
newItem: { name: '', age: '' }
}
},
methods: {
addRow() {
if (this.newItem.name && this.newItem.age) {
this.tableData.push({...this.newItem})
this.newItem = { name: '', age: '' }
}
},
deleteRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
表单验证(可选)
添加简单的表单验证确保输入有效性:
methods: {
addRow() {
if (!this.newItem.name.trim()) {
alert('请输入姓名')
return
}
if (isNaN(this.newItem.age) || this.newItem.age <= 0) {
alert('年龄必须为正数')
return
}
this.tableData.push({
name: this.newItem.name,
age: Number(this.newItem.age)
})
this.newItem = { name: '', age: '' }
}
}
使用计算属性(可选)
如果需要过滤或处理表格数据,可以使用计算属性:
computed: {
filteredData() {
return this.tableData.filter(item => item.age > 18)
}
}
注意事项
- 为
v-for设置唯一的key属性以提高性能 - 对于大型数据集考虑使用虚拟滚动优化性能
- 复杂场景可结合 Vuex 进行状态管理
- 实际项目中建议使用第三方表格组件如 Element UI 的 el-table
通过以上方式即可在 Vue 中实现基本的表格增删功能。根据项目需求,可以进一步扩展编辑、排序、分页等功能。






