需求场景:在Vue+Elementui项目中,需要在表单的循环数组中,对某一深层嵌套的对象属性制定自定义校验规则。文章来源地址https://www.toymoban.com/news/detail-745676.html
<template>
<div>
<el-form :model="form" ref="form" label-width="110px">
<div v-for="(item,index) in form.list" :key="index">
<el-col :xs="24"
:sm="24"
:md="12"
:lg="4">
<el-form-item label="默认值" :prop="`list.${index}.state`" :rules="{ required:true, validator: validateState, trigger: 'blur', index:index }">
<el-input v-model.number="item.state"></el-input>
</el-form-item>
</el-col>
<el-col :xs="24"
:sm="24"
:md="11"
:lg="5">
<el-form-item label="是否可调">
<el-switch active-text="是" inactive-text="否" v- model="item.adjust.isAdjust">
</el-switch>
</el-form-item>
</el-col>
<el-col :xs="24"
:sm="24"
:md="12"
:lg="8"
v-show="item.adjust.isAdjust">
<el-form-item label="范围调节" required>
<el-col :span="11">
<el-form-item :prop="`list.${index}.adjust.min`" :rules="{ required:true, validator: validateMin, trigger: 'blur', index:index }">
<el-input v-model.number="item.adjust.min"
placeholder="最小值">
</el-input>
</el-form-item>
</el-col>
<el-col :span="1">
<div style="text-align:center;">至</div>
</el-col>
<el-col :span="11">
<el-form-item :prop="`list.${index}.adjust.max`" :rules="{ required:true, validator: validateMax, trigger: 'blur', index:index }">
<el-input v-model.number="item.adjust.max"
placeholder="最大值">
</el-input>
</el-form-item>
</el-col>
</el-form-item>
</el-col>
</div>
</el-form>
</div>
</template>
<script>
export default{
data(){
return{
// 此处略过。。。挪用上文
}
},
methods:{
isEmpty(arg) {
if(typeof arg === 'undefined' || arg === null || arg === ''){
return true
}
return false
},
validateState(rule,value,callback){
let min = this.form.list[rule.index].adjust.min
let max = this.form.list[rule.index].adjust.max
if(this.isEmpty(value)) {
return callback(new Error('参数不得为空')))
}
if(!this.isEmpty(min) && !this.isEmpty(max) && parseInt(value) <
parseInt(min)) {
return callback(new Error('不得小于最小值')))
}
if(!this.isEmpty(min) && !this.isEmpty(max) && parseInt(value) > parseInt(max)) {
return callback(new Error('不得大于最大值'))
}
return callback()
},
}
}
</script>
文章来源:https://www.toymoban.com/news/detail-745676.html
到了这里,关于vue+elementui表单数组对象深层嵌套之自定义验证规则的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!