vue实现表格添加
使用 Vue 实现表格添加功能
数据绑定与表格渲染
在 Vue 中通过 v-model 绑定表单输入数据,使用 v-for 渲染表格。初始化一个空数组 tableData 存储表格数据,并通过双向绑定动态更新。
<template>
<div>
<input v-model="newItem.name" placeholder="名称">
<input v-model="newItem.age" placeholder="年龄">
<button @click="addItem">添加</button>
<table>
<tr>
<th>名称</th>
<th>年龄</th>
</tr>
<tr v-for="(item, index) in tableData" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</table>
</div>
</template>
添加数据方法
在 Vue 实例的 methods 中定义 addItem 方法,将新数据推入 tableData 数组,并清空输入框。

<script>
export default {
data() {
return {
newItem: { name: '', age: '' },
tableData: []
}
},
methods: {
addItem() {
if (this.newItem.name && this.newItem.age) {
this.tableData.push({...this.newItem});
this.newItem = { name: '', age: '' };
}
}
}
}
</script>
数据验证
添加简单的非空验证,确保用户输入有效数据后再执行添加操作。
methods: {
addItem() {
if (!this.newItem.name.trim() || !this.newItem.age.trim()) {
alert('请填写完整信息');
return;
}
this.tableData.push({...this.newItem});
this.newItem = { name: '', age: '' };
}
}
使用计算属性优化
若需对表格数据进行过滤或排序,可通过计算属性实现,避免直接修改原始数据。

computed: {
sortedData() {
return [...this.tableData].sort((a, b) => a.age - b.age);
}
}
组件化拆分
对于复杂表格,可将表格行拆分为子组件,通过 props 传递数据,提高代码可维护性。
<template>
<tr>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</template>
<script>
export default {
props: ['item']
}
</script>
响应式更新注意事项
Vue 2 中直接通过索引修改数组元素时需使用 Vue.set 确保响应式更新。Vue 3 中使用 reactive 或 ref 自动处理。
// Vue 2
Vue.set(this.tableData, index, newValue);
// Vue 3
const tableData = ref([]);
tableData.value[index] = newValue; // 自动响应






