Vue项目element-ui 添加动态校验
需求:一个表单中某个字段,根据另一个字段变化,校验是否必填
<el-form ref="detail" :model="detail" :rules="ruleData" size="small" label-width="100px">
<el-card>
<el-row>
<el-col :span="12">
<el-form-item label="范围" prop="type" label-width="220px">
<el-select v-model="detail.type" style="width: 100%" clearable placeholder="请选择" @change="typeChange()">
<el-option label="分步" value="01"> </el-option>
<el-option label="最终" value="02"> </el-option>
</el-select>
</el-form-item>
</el-col>
<el-col :span="12">
<el-form-item label="数量" prop="number" label-width="220px">
<el-input v-model="detail.number" type="number" style="width: 100%"> </el-input>
</el-form-item>
</el-col>
</el-row>
</el-card>
</el-form>
typeChange () { if (String(this.detail.type) === '02') { this.$delete(this.ruleData, 'number'); } else { this.ruleData = { ...this.rules, number: this.otherRule.number }; } (this.$refs.detail as any).clearValidate(); } rules = { type: [{ required: true, message: '请选择', trigger: 'blur' }], }; otherRule = { number: [{ required: true, message: '请输入', trigger: 'blur' }], }; ruleData = { ...this.rules, number: this.otherRule.number };