需求:表单有俩个按钮,一个是全部添加,一个是部分添加默认如下:
点击添加饮品爱好后如下,可以添加多个
点击添加全部,并且点击提交按钮后的表单校验,如下图:
全部代码如下,可自行复制查看
<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>
得到的数据结构如下图,不会影响,都是单独的表单验证:
这样就实现啦,文章到此结束,希望对你有所帮助~~文章来源:https://www.toymoban.com/news/detail-480190.html
文章来源地址https://www.toymoban.com/news/detail-480190.html
到了这里,关于el-form表单全部/部分添加一样字段内容并表单校验(复制即可实现)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!