vue实现多行多个表单
Vue 实现多行多个表单
在 Vue 中实现多行多个表单通常需要动态生成表单字段,并管理表单数据。以下是几种常见的方法:
动态表单字段绑定
使用 v-for 动态生成表单字段,结合 v-model 绑定数据:
<template>
<div>
<div v-for="(row, rowIndex) in formData" :key="rowIndex">
<input v-for="(field, fieldIndex) in row.fields"
:key="fieldIndex"
v-model="field.value"
:placeholder="field.placeholder">
</div>
<button @click="addRow">添加一行</button>
</div>
</template>
<script>
export default {
data() {
return {
formData: [
{
fields: [
{ value: '', placeholder: '字段1' },
{ value: '', placeholder: '字段2' }
]
}
]
}
},
methods: {
addRow() {
this.formData.push({
fields: [
{ value: '', placeholder: '字段1' },
{ value: '', placeholder: '字段2' }
]
})
}
}
}
</script>
使用组件封装表单行
将每行表单封装为独立组件,提高代码复用性:
<template>
<div>
<FormRow
v-for="(row, index) in rows"
:key="index"
:fields="row.fields"
@update="updateRow(index, $event)"
/>
<button @click="addRow">添加一行</button>
</div>
</template>
<script>
import FormRow from './FormRow.vue'
export default {
components: { FormRow },
data() {
return {
rows: [
{ fields: [{ value: '' }, { value: '' }] }
]
}
},
methods: {
addRow() {
this.rows.push({ fields: [{ value: '' }, { value: '' }] })
},
updateRow(index, updatedFields) {
this.rows[index].fields = updatedFields
}
}
}
</script>
表单验证
结合 Vuelidate 或 Vue 自带的验证机制实现表单验证:
<template>
<div>
<div v-for="(row, rowIndex) in formData" :key="rowIndex">
<input
v-model="row.field1"
:class="{ 'error': $v.formData[rowIndex].field1.$error }">
<span v-if="$v.formData[rowIndex].field1.$error">字段必填</span>
</div>
</div>
</template>
<script>
import { required } from 'vuelidate/lib/validators'
export default {
data() {
return {
formData: [{ field1: '' }]
}
},
validations: {
formData: {
$each: {
field1: { required }
}
}
}
}
</script>
提交表单数据
处理表单提交时,遍历所有行数据:
methods: {
submitForm() {
const allData = this.formData.map(row => {
return {
field1: row.field1,
field2: row.field2
}
})
console.log('提交的数据:', allData)
// 发送到API等操作
}
}
注意事项
- 为动态生成的表单元素添加唯一的
key属性,确保 Vue 能正确追踪节点 - 复杂表单建议使用 Vuex 或 Pinia 管理状态
- 对于大量表单数据,考虑分页或懒加载优化性能
- 移动端适配时注意表单布局和输入体验







