vue实现多行多个表单
Vue 实现多行多个表单
在 Vue 中实现多行多个表单,通常需要动态生成表单字段,并确保数据绑定和提交逻辑正确。以下是实现方法:
动态表单数据绑定
使用 v-for 动态渲染多行表单,并通过 v-model 绑定数据。数据通常存储在一个数组中,每个元素代表一行表单的数据。

<template>
<div>
<div v-for="(row, index) in formRows" :key="index">
<input v-model="row.field1" placeholder="Field 1">
<input v-model="row.field2" placeholder="Field 2">
<button @click="removeRow(index)">Remove</button>
</div>
<button @click="addRow">Add Row</button>
<button @click="submitForm">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
formRows: [
{ field1: '', field2: '' }
]
}
},
methods: {
addRow() {
this.formRows.push({ field1: '', field2: '' });
},
removeRow(index) {
this.formRows.splice(index, 1);
},
submitForm() {
console.log(this.formRows);
}
}
}
</script>
表单验证
如果需要表单验证,可以使用 Vue 的 computed 属性或第三方库如 Vuelidate 来检查数据有效性。

<template>
<div>
<div v-for="(row, index) in formRows" :key="index">
<input v-model="row.field1" placeholder="Field 1">
<span v-if="!row.field1 && showError">Field 1 is required</span>
<input v-model="row.field2" placeholder="Field 2">
<span v-if="!row.field2 && showError">Field 2 is required</span>
<button @click="removeRow(index)">Remove</button>
</div>
<button @click="addRow">Add Row</button>
<button @click="validateForm">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
formRows: [
{ field1: '', field2: '' }
],
showError: false
}
},
methods: {
addRow() {
this.formRows.push({ field1: '', field2: '' });
},
removeRow(index) {
this.formRows.splice(index, 1);
},
validateForm() {
this.showError = true;
const isValid = this.formRows.every(row => row.field1 && row.field2);
if (isValid) {
this.submitForm();
}
},
submitForm() {
console.log(this.formRows);
}
}
}
</script>
使用组件封装
对于复杂的表单,可以将单行表单封装为一个组件,提高代码复用性。
<template>
<div>
<FormRow
v-for="(row, index) in formRows"
:key="index"
:rowData="row"
@remove="removeRow(index)"
/>
<button @click="addRow">Add Row</button>
<button @click="submitForm">Submit</button>
</div>
</template>
<script>
import FormRow from './FormRow.vue';
export default {
components: { FormRow },
data() {
return {
formRows: [
{ field1: '', field2: '' }
]
}
},
methods: {
addRow() {
this.formRows.push({ field1: '', field2: '' });
},
removeRow(index) {
this.formRows.splice(index, 1);
},
submitForm() {
console.log(this.formRows);
}
}
}
</script>
表单提交与数据处理
提交表单时,可以将数据发送到后端或进行本地处理。确保数据格式符合要求。
methods: {
submitForm() {
const payload = {
rows: this.formRows
};
axios.post('/api/submit', payload)
.then(response => {
console.log('Success:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
}
}
通过以上方法,可以灵活实现多行多个表单的功能,并根据需求扩展验证、提交等逻辑。






