<template> <div id="app"> <el-form ref="form" :model="form" :rules="rules" label-width="80px"> <el-form-item label="活动名称" prop="name"> <el-input v-model="form.name" @blur="blur()"></el-input> </el-form-item> <el-form-item label="具体活动" prop="name1"> <el-input v-model="form.name1"></el-input> </el-form-item> </el-form> </div> </template> <script> export default { name: "app", components: {}, data() { return { form: { name: "", name1: "", }, rules: {}, }; }, methods: { addRules() { // 定义规则 const newRules = [{ required: true, trigger: "change", message: "具体活动必填" }]; // 给rules对象添加规则 this.rules = { ...this.rules, name1: newRules }; }, removeRules() { // 清除指定校验规则 this.$refs.form.clearValidate(["name1"]); // 这行必须 this.rules = { ...this.rules, name1: [] }; }, blur() { if (this.form.name === "") { this.removeRules(); } else { this.addRules(); } }, }, }; </script>
效果:
活动名称为空时,具体活动选项非必填
活动名称不为空时,具体活动选项必填