vue实现输入表格
Vue 实现输入表格的方法
在 Vue 中实现输入表格可以通过多种方式完成,常见的是结合 v-for 指令和双向数据绑定 v-model。以下是几种实现方法:
动态绑定表格数据
使用 v-for 动态渲染表格行,并通过 v-model 绑定输入框的值到 Vue 的数据对象。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="index">
<td><input v-model="row.name" type="text" /></td>
<td><input v-model="row.age" type="number" /></td>
<td><button @click="removeRow(index)">删除</button></td>
</tr>
</tbody>
</table>
<button @click="addRow">添加行</button>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '', age: '' }
]
}
},
methods: {
addRow() {
this.tableData.push({ name: '', age: '' })
},
removeRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
使用组件化表格
将表格行封装为单独的组件,便于复用和管理逻辑。
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<TableRow
v-for="(row, index) in tableData"
:key="index"
:row="row"
@remove="removeRow(index)"
/>
</tbody>
</table>
<button @click="addRow">添加行</button>
</template>
<script>
import TableRow from './TableRow.vue'
export default {
components: { TableRow },
data() {
return {
tableData: [
{ name: '', age: '' }
]
}
},
methods: {
addRow() {
this.tableData.push({ name: '', age: '' })
},
removeRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
使用第三方表格库
对于复杂需求,可以集成第三方表格库如 Element UI 或 VxeTable。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名">
<template #default="{ row }">
<el-input v-model="row.name" />
</template>
</el-table-column>
<el-table-column prop="age" label="年龄">
<template #default="{ row }">
<el-input v-model.number="row.age" type="number" />
</template>
</el-table-column>
<el-table-column label="操作">
<template #default="{ $index }">
<el-button @click="removeRow($index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-button @click="addRow">添加行</el-button>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '', age: '' }
]
}
},
methods: {
addRow() {
this.tableData.push({ name: '', age: '' })
},
removeRow(index) {
this.tableData.splice(index, 1)
}
}
}
</script>
注意事项
- 确保
v-model绑定的数据类型正确,如数字类型需使用v-model.number。 - 动态添加或删除行时,避免直接修改数组引用,应使用响应式方法如
push或splice。 - 对于大型表格,考虑性能优化,如虚拟滚动或分页加载。







