el-form表单动态校验
el-form常规校验方式:
// 结构部分
<el-form ref="form" :model="form" :rules="rules">
<el-form-item label="活动名称: " prop="name" required>
<el-input v-model="form.name" />
</el-form-item>
</el-form>
// script部分
<script>
export default {
data() {
return {
form: {},
rules: {
name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }]
}
}
}
}
save() {
this.$refs.form.validate((valid) => {
if (valid) {
console.log('通过表单校验')
}
})
}
正题部分-表单动态校验
场景: 输入框根据单选项来动态校验表单
没有选中的选项就不用校验
效果:
<el-form ref="form" :model="form" :rules="rules">
<el-form-item label="跳转类型: " prop="skipType" required>
<el-radio-group v-model="form.skipType"">
<el-radio :label="0" style="display: block; margin: 10px 0">无跳转</el-radio>
<div>
<el-radio :label="1" style="display: inline-block; margin: 11px 0">小程序内页</el-radio>
<el-form-item
label=""
label-width="0"
style="display: inline-block; height:20px"
prop="insidePage"
:rules="form.skipType === 1 ? rules.insidePage : []"
:required="form.skipType === 1"
>
<!-- :rules="[{ required: true, message: '请输入小程序页面路径', trigger: 'blur' }]" -->
<el-input
v-model.trim="form.insidePage"
placeholder="输入小程序页面路径"
autocomplete="off"
maxlength="20"
style="width: 160px; margin-left: 10px"
/>
</el-form-item>
</div>
<div>
<el-radio :label="2" style="display: inline-block; margin: 11px 0 14px">外部小程序</el-radio>
<el-form-item
label=""
label-width="0"
style="display: inline-block"
prop="outsideAppId"
:rules="form.skipType === 2 ? rules.outsideAppId : []"
:required="form.skipType === 2"
>
<el-input
v-model.trim="form.outsideAppId"
placeholder="输入小程序APPID"
autocomplete="off"
maxlength="20"
style="width: 160px; margin-left: 10px"
/>
</el-form-item>
</div>
</el-radio-group>
</el-form-item>
</el-form>
// script部分
<script>
export default {
data() {
return {
form: {},
rules: {
skipType: [{ required: true, message: '请选择跳转类型', trigger: 'change' }],
insidePage: [{ required: true, message: '请输入小程序页面路径', trigger: 'blur' }],
outsideAppId: [{ required: true, message: '请输入小程序appid', trigger: 'blur' }]
}
}
}
}
save() {
this.$refs.form.validate((valid) => {
if (valid) {
console.log('通过表单校验')
}
})
}
关键点: 跟正常校验流程不同的是, el-form-item标签内的required和rules都要加上判断条件
:rules="form.skipType === 1 ? rules.insidePage : []" :required="form.skipType === 1"