Problem Description
The form component used elementui
, if several of the form items are used v-if进行UI切换,并且默认v-if="false"不可见,切换的元素又是必填项时
, then a very strange bug will appear during verification.
reason:
elementui
校验规则绑定
It isvue声明周期mounted
done when performing subcomponents with prop attributes in the form form . The elements used by v-if to switch will be destroyed, resulting in the form items in v-if, since they are not rendered during the mounted period, the rules are not bound.
Thenel-form-item
use the rules for dynamic binding`, once you switch, you will bind the rules.
Another pitfall, in the custom verification method, for example
validLandlordName(rule, value, callback) {}
, sometimes the value of value cannot be obtained and is empty. Then directly obtain the attribute value you enteredthis.houseInfo.landlord.landlordName
for verification, and don't judge the value anymore.
<el-form ref="form" :rules="rules" :model="houseInfo" inline size="mini" label-width="150px">
<el-row>
<el-col>
<el-form-item label="所属社区" label-width="150px" prop="communityId">
<el-select v-model.trim="houseInfo.communityId" placeholder="所属社区" :disabled="true">
<el-option v-for="item in communityList" :value="item.communityId" :label="item.communityName" :key="item.communityId">
</el-option>
</el-select>
</el-form-item>
</el-col>
</el-row>
<!-- houseInfo.houseType 值为4-->
<el-row v-if="houseInfo.houseStatus == 4">
<el-col>
<el-form-item label="所属楼栋/单元" prop="buildingId" label-width="150px">
<el-cascader placeholder="所属楼栋/单元" :disabled="houseTypeDisabled" :options="deptTreeBuilding" v-model="houseInfo.selectOptions"
@change="selectedBuildingChanged" :change-on-select="true" style="width:200px">
</el-cascader>
</el-form-item>
</el-col>
</el-row>
<el-row>
<!-- 此时这个手机号码,默认是不显示的,一旦切换渲染出来,验证规则不做特殊处理就会报错-->
<div v-if="houseInfo.houseStatus !== 4">
<el-row>
<el-col>
<el-form-item label="手机号码" prop="landlord.contactMobile" >
<el-input v-model="houseInfo.landlord.contactMobile" style="width:200px" placeholder="请输入手机号码"></el-input>
</el-form-item>
</el-col>
</el-row>
</div>
</el-form>
Solution:
For the form elements in v-if, use dynamic validation rules to bind: rule=[XXX], and customize the validation method in method at the same time.
------ If the article is useful to you, thank you in the upper right corner >>>Like|Favorite <<<