vue实现表格数据增删
Vue 实现表格数据增删的方法
数据绑定与渲染
在Vue中,表格数据通常通过v-for指令动态渲染。定义一个数组tableData存储表格数据,使用v-for循环渲染每一行。
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
<button @click="deleteRow(index)">Delete</button>
</td>
</tr>
</tbody>
</table>
<button @click="addRow">Add Row</button>
</template>
新增数据
通过push方法向tableData中添加新数据。新增的数据可以来自表单输入或固定值。
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
],
nextId: 3
};
},
methods: {
addRow() {
this.tableData.push({
id: this.nextId++,
name: `New User ${this.nextId}`
});
}
}
};
</script>
删除数据
使用splice方法根据索引删除指定行数据。通过传递index参数定位要删除的行。
methods: {
deleteRow(index) {
this.tableData.splice(index, 1);
}
}
完整示例
结合新增和删除功能,以下是一个完整的Vue组件示例:

<template>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
<button @click="deleteRow(index)">Delete</button>
</td>
</tr>
</tbody>
</table>
<button @click="addRow">Add Row</button>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
],
nextId: 3
};
},
methods: {
addRow() {
this.tableData.push({
id: this.nextId++,
name: `New User ${this.nextId}`
});
},
deleteRow(index) {
this.tableData.splice(index, 1);
}
}
};
</script>
注意事项
- 唯一键值:确保
v-for中的:key使用唯一标识(如id),避免渲染性能问题。 - 响应式更新:Vue会自动检测数组变化并更新DOM,直接使用
push、splice等方法即可。 - 表单输入:如需通过表单输入新增数据,可通过
v-model绑定输入框值,再添加到tableData中。






