需求:表单有俩个按钮,一个是全部添加,一个是部分添加默认如下:
点击添加饮品爱好后如下,可以添加多个
点击添加全部,并且点击提交按钮后的表单校验,如下图:
全部代码如下,可自行复制查看
<template>
<!-- 全部添加和部分添加 -->
<div class="content-box">
<div class="container">
<p>主题页面 1 - 1</p>
<el-row>
<el-col :span="9">
<div class="table-container">
<el-form ref="form" :model="form1" label-width="100px">
<div v-for="(item, index) in form1.items" :key="index">
<el-form-item
label="姓名"
:prop="'items.' + index + '.name'"
:rules="{ required: true, message: '姓名不能为空', trigger: 'blur' }"
>
<el-input v-model="item.name"></el-input>
</el-form-item>
<el-form-item
label="年龄"
:prop="'items.' + index + '.age'"
:rules="{ required: true, message: '年龄不能为空', trigger: 'blur' }"
>
<el-input v-model="item.age"></el-input>
</el-form-item>
<div v-for="(text, i) in item.itemall" :key="i">
<el-form-item
label="饮品---"
:prop="'items.' + index + '.itemall.' + i + '.drink'"
:rules="{ required: true, message: '饮品不能为空', trigger: 'blur' }"
>
<el-input v-model="text.drink"></el-input>
</el-form-item>
<el-form-item
label="爱好---"
:prop="'items.' + index + '.itemall.' + i + '.hobby'"
:rules="{ required: true, message: '爱好不能为空', trigger: 'blur' }"
>
<el-input v-model="text.hobby"></el-input>
</el-form-item>
</div>
<el-form-item>
<el-button type="primary" @click="addItem(index)">添加饮品爱好</el-button>
</el-form-item>
</div>
<el-form-item>
<template>
<el-button type="primary" @click="addAll">添加全部</el-button>
<el-button type="primary" @click="submitForm">提交</el-button>
</template>
</el-form-item>
</el-form>
</div>
</el-col>
</el-row>
<div class="pagination-area"></div>
</div>
</div>
</template>
<script>
import { testApi } from '@/api/test';
const defaultListQuery = {
pageNum: 1,
pageSize: 10,
keyword: ''
};
export default {
data() {
return {
form1: {
items: [
{
name: '',
age: '',
itemall: [{ drink: '', hobby: '' }]
}
// { name: '', itemall: [{ sexs: '', age: '' }] }
]
},
form: {
name: '',
age: '',
items: [{ sex: '', hobby: '' }]
},
argList: []
};
},
created() {},
methods: {
// 添加表单内容操作
addItem(index) {
console.log(index);
this.form1.items[index].itemall.push({
drink: '',
hobby: ''
});
},
// 提交做校验
submitForm() {
this.$refs.form.validate((valid) => {
if (valid) {
console.log(this.form1, '数据结构');
} else {
console.log('表单验证失败');
}
});
},
addAll() {
this.form1.items.push({
name: '',
age: '',
itemall: [{ drink: '', hobby: '' }]
});
}
}
};
</script>
得到的数据结构如下图,不会影响,都是单独的表单验证:
这样就实现啦,文章到此结束,希望对你有所帮助~~