vueelementUI form组件动态添加el-form-item并且动态添加rules必填项校验方法
先看一下效果图(想在表单里动态的增删 form-item,然后添加rules,校验其必填项;
):
<div v-for="(item, index) in form.labels" :key="index" class="label">
<el-form-item label="名称:"
:prop="'labels.' + index + '.name'"
:rules="{
required: true, message: '请输入', trigger: 'blur'
}"
class="middleInput">
<el-input v-model.trim="item.name" maxlength="30" placeholder="请输入"></el-input>
<i class="el-icon-circle-plus-outline icon" v-if="(index === (form.labels.length - 1))" @click.prevent="addKey(item)"></i>
<i class="el-icon-remove-outline icon" v-if="(form.labels.length > 1)" @click.prevent="removeKey(item, index)"></i>
</el-form-item>
<el-form-item label="值:"
:prop="'labels.' + index + '.value'"
:rules="{
required: true, message: '请输入', trigger: 'blur'
}"
class="middleInput">
<el-input maxlength="100" show-word-limit type="textarea" :rows="3" v-model.trim="item.value" placeholder="请输入"></el-input>
</el-form-item>
</div>
//data:
form: {
labels: [{
name: '',
value: ''
}]
},
// methods:
addKey (item) {
this.form.labels.push({
name: '',
value: ''
})
},
removeKey (item, index) {
this.form.labels.splice(index, 1)
},
注意
核心代码:
:prop="'labels.' + index + '.name'"
:rules="{
required: true, message: '请输入', trigger: 'blur'
}"
- prop里的值有格式要求,以本demo为例:"表单属性数组key名 + '.' + 索引值 + '.' + 数组里对象的key名";
- rules里填写校验不成功触发条件和提示语;
参考:vue elementUI form组件动态添加el-form-item rules且支持添加自定义校验方法-CSDN博客