javascript
<template>
<div>
<el-form :model="form" :rules="rulse" ref="form" :inline="true">
<el-form-item label="用户aaa" prop="aaa">
<el-input v-model="form.aaa" class="w-220" @input="input"></el-input>
</el-form-item>
<!-- 循环的表单 -->
{{this.form.subjects.length}}
<div v-for="(item,index) in form.subjects" :key="index" class="subjects">
<el-form :model="item" :rules="rulse" :ref=" 'subjects' + index ">
<el-form-item label="用户bbb" prop="bbb">
<el-input v-model="item.bbb" class="w-220"></el-input>
</el-form-item>
<el-form-item label="用户ccc" prop="ccc">
<el-input v-model="item.ccc" class="w-220"></el-input>
</el-form-item>
</el-form>
</div>
<el-form-item>
<el-button type="primary" @click="submitForm()">提交</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
data () {
var count20 = (rule, value, callback) => {
if (value && !/^[0-9]{1,2}$/.test(value)) {
callback(new Error("请填写1-20的数字"));
} else if (value < 1 || value > 20) {
callback(new Error("请填写1-20的数字"));
} else {
callback();
}
}
return {
form: {
aaa: '',
subjects: [
{
bbb: '',
ccc: ''
}
]
},
rulse: {
aaa: [
{ required: true, validator: count20, trigger: 'blur' }
],
bbb: [
{ required: true, message: '请输入', trigger: 'blur' }
],
ccc: [
{ required: true, message: '请输入', trigger: 'blur' }
]
}
}
},
methods: {
// 只能新增3个
input (value) {
// 循环的表单总数
const count = this.form.subjects.length
if (/^[0-9]{1,2}$/.test(value) && value <= 3) {
if (value > count) {
// 追加
const countNumber = Number(value) - Number(count)
for (let i = 0; i < countNumber; i++) {
this.form.subjects.push(
{
bbb: '',
ccc: ''
}
)
}
} else if (value < count) {
this.form.subjects = this.form.subjects.slice(0, value)
}
}
},
// 提交
submitForm () {
// 校验是否全部通过
let validd = true;
this.$refs.form.validate((valid) => {
if (!valid) {
validd = false
}
})
if (this.form.subjects.length) {
for (var i = 0; i < this.form.subjects.length; i++) {
this.$refs["subjects" + i][0].validate((valid) => {
if (!valid) {
validd = false
}
})
}
}
// 全部校验通过
if (validd) {
console.log(this.form)
}
}
}
}
</script>
<style lang="less" scoped>
.subjects {
border: 1px solid black;
border-radius: 10px;
padding: 20px;
box-sizing: border-box;
}
</style>