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="年龄" type="number" />
<button @click="addRow">添加</button>
</div>
</div>
</template>
添加数据方法
定义 addRow 方法,将表单输入的新数据添加到表格数据数组中。添加前可进行简单校验,防止空数据。
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 }
],
newItem: { name: '', age: '' }
}
},
methods: {
addRow() {
if (!this.newItem.name || !this.newItem.age) return
this.tableData.push({ ...this.newItem })
this.newItem = { name: '', age: '' } // 清空表单
}
}
}
</script>
删除数据方法
通过 deleteRow 方法,根据行索引从表格数据数组中移除对应项。使用 splice 方法确保响应式更新。
methods: {
deleteRow(index) {
this.tableData.splice(index, 1)
}
}
完整组件示例
整合上述代码,形成完整组件。包含表格渲染、添加和删除功能,并处理基础输入校验。
<template>
<div>
<table border="1">
<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 style="margin-top: 20px">
<input v-model="newItem.name" placeholder="姓名" />
<input v-model="newItem.age" placeholder="年龄" type="number" />
<button @click="addRow">添加</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 25 }
],
newItem: { name: '', age: '' }
}
},
methods: {
addRow() {
if (!this.newItem.name || !this.newItem.age) {
alert('请填写完整信息')
return
}
this.tableData.push({ ...this.newItem })
this.newItem = { name: '', age: '' }
},
deleteRow(index) {
if (confirm('确定删除吗?')) {
this.tableData.splice(index, 1)
}
}
}
}
</script>
关键点说明
- 响应式数据:Vue 自动跟踪
tableData的变化,更新 DOM。 - 列表渲染:
v-for需配合:key提升性能,通常使用唯一标识而非索引。 - 方法逻辑:添加时需处理对象引用,避免直接修改
newItem导致后续数据联动。 - 用户交互:删除前通过
confirm确认,提升用户体验。







