存在一排必填,点击增加后会新增一行,点击每行后面的删除图标则会删除该行,新增按钮只会出现在最后一行
<el-form ref="form" :rules="formRules" :inline="true" :model="form" label-width="80px">
<div v-for="(item, index) in form.dynamicItem" :key="index">
<el-form-item
label="姓名"
:prop="'dynamicItem.' + index + '.name'"
:rules="{
required: true, message: '姓名不能为空', trigger: 'blur'
}"
>
<el-input v-model="item.name"></el-input>
</el-form-item>
<el-form-item
label="手机号"
:prop="'dynamicItem.' + index + '.phone'"
:rules="[
{required: true, message: '手机号不能为空', trigger: 'blur'},
{ pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
]"
>
<el-input v-model="item.phone"></el-input>
</el-form-item>
<el-form-item>
<el-button v-if="index+1 == form.dynamicItem.length" @click="addItem" type="primary">增加</el-button>
<el-button v-if="index !== 0" @click="deleteItem(item, index)" type="danger">删除</el-button>
</el-form-item>
</div>
</el-form>
data中定义,默认添加一条
form: {
dynamicItem: [
{
name: "",
phone: ""
}
]
},
methods方法
addItem() {
this.form.dynamicItem.push({
name: "",
phone: ""
});
},
sure(form) {
console.log(this.form.dynamicItem.length, "length");
this.$refs[form].validate(valid => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
deleteItem(item, index) {
this.form.dynamicItem.splice(index, 1);
console.log(this.form.dynamicItem, "删除");
},