Avue组件或Element-UI动态修改rules验证规则或根据条件修改rules验证规则
根据条件修改验证规则:el-form中若A为空,则B可为空,若A有值,则B必填,动态改变B的验证规则。
·
AVUE组件或el-form动态修改rules验证规则
问题描述
根据条件修改验证规则:el-form中若A为空,则B可为空,若A有值,则B必填,动态改变B的验证规则
问题的解决原理
avue:
在watch监听事件中,使用auve-form自带的:defaults.sync="defaults"属性,来操作B的rules验证规则,此写法的效果好于el-form原生,因为设置为必填后会有必填标志*
el-form:
使用watch监听A值的变化,若A不为空,则操作B的验证规则(万金油)
tip:如果使用select单选框组件,也可在单选框@change事件中操作B的验证规则(特殊)
代码如下
Avue组件中:
//此处用applyType指代a ,taxNumber 指代B
<avue-form :defaults.sync="defaults" v-model="modifyForm" :option="modifyOption" @submit="modificationSubmission"></avue-form>
...
data(){
return{
defaults:{},
//avue配置项
modifyOption: {
submitText:'修改申报',
menuPosition:'right',
size:"mini",
labelWidth:150,
emptyBtn:false,
column: [
{
label: '申报类型',
prop: 'applyType',
type: 'radio',
span:24,
rules: [{
required: true,
message: "请选择申报类型",
trigger: "blur"
}],
dicData: radioList
}]
}
}
}
...
watch:{
'modifyForm.applyType'(val){
if(val=== null || val === undefined || val === ''){
//此处绑定的rules规则参考默认绑定rules
this.defaults.taxNumber.rules = [
{required: false,
validator: validateCode1,
trigger: "blur"}
]
}else{
this.defaults.taxNumber.rules = [
{required: true,
validator: validateCode1,
trigger: "blur"}
]
}
}
el-form原生组件中:
<el-form ref="ruleForm" :rules="rules" :model="form" label-width="220px">
<el-form-item label="申报园区:" prop="applyPark">
<el-select v-model="form.applyPark" placeholder="请选择" @change="changeApplyPark">
<el-option
v-for="item in applyList"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</el-form-item>
<el-form-item label="社会统一信用代码:" prop="taxNumber">
<el-input v-model="form.taxNumber"></el-input>
</el-form-item>
</el-form>
...
export default{
data(){
return{
applyList :[{
label:'公司',
value:0
},{
label:'分公司',
value:1
}],
//rules中要先声明一个不必填,否则下面的this.rules.taxNumber取不到
rules: {
applyPark: [
{required: true, message: "请选择申报类型", trigger: "blur"},
],
taxNumber: [
{required: false, message: "请输入社会统一信用代码", trigger: "blur"},
],
}
}
},
methods:{
changeApplyPark(){
if(this.form.applyPark === null || this.form.applyPark === undefined || this.form.applyPark === ''){
this.rules.taxNumber = [
{required: false, message: "请输入社会统一信用代码", trigger: "blur"}
]
}else{
this.rules.taxNumber = [
{required: true, message: "请输入社会统一信用代码", trigger: "blur"}
]
}
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)