参考链接:https://dsx2016.com/?p=529
<el-form-item label="发票类型" prop="billType">
<el-select v-model="applyData.billType" collapse-tags @change="changeType">
<el-option v-for="item in applyData.billTypeOption" :key="item.key" :label="item.val" :value="item.key" >
</el-option>
</el-select>
</el-form-item>
<el-form-item label="开票电话" prop="invoicePhone" :required="isHaveTo">
<el-input v-model="applyData.invoicePhone" maxlength="20"></el-input>
</el-form-item>
const isnvoicePhone = (rule, value, callback) => {
// 当为空值且为必填时,抛出错误,反之通过校验
if (this.applyData.invoicePhone === '' && this.isHaveTo) {
callback(new Error('请输入开票电话'));
} else {
callback();
}
};
invoicePhone: [
{ validator: isInvoicePhone },
],
computed: {
isHaveTo() {
return this.applyData.billType === 0;
},
},
changeType() {
// 重置数据
this.applyData.invoicePhone = ''
this.$nextTick(() => {
// 移除校验结果
this.$refs.applyData.clearValidate();
})
},
在changeType时清除校验,并通过isHaveTo来控制输入框是否必填,并在自定义校验中当是必填项并且为空时返回错误信息