业务场景:
**活动区域下拉框的值,选择为区域二时,显示活动形式(必填项)。
活动区域下拉框的值,选择为区域一时,活动形式则隐藏,因为活动形式为必填项,点保存是走ruleForm检验valid返回false,所以下面代码会报错走 console.log(‘error submit!!’);
**
解决方案如下:
使用>> :rules={}
:rules="rules" //注意:rules不能改 ;
后面的rules要与data=>return里rules名称相同,根据自己情况写 ;
里面的prop也不能少;
:model="ruleForm"也不能少
<el-form-item label="活动形式" prop="desc" v-show="ruleForm.region==2" :rules="{required:changeValue=='2?true:false,message:'请填写活动形式'}">
<el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="活动区域" prop="region">
<el-select v-model="ruleForm.region" placeholder="请选择活动区域">
<el-option label="区域一" value="1"></el-option>
<el-option label="区域二" value="2"></el-option>
</el-select>
</el-form-item>
<el-form-item label="活动形式" prop="desc" v-show="ruleForm.region==2" :rules="{required:changeValue=='2?true:false,message:'请填写活动形式'}">
<el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
<el-button @click="resetForm('ruleForm')">取消</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
changeValue: '',
ruleForm: {
name: '',
region: '',
desc: ''
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
region: [
{ required: true, message: '请选择活动区域', trigger: 'change' }
],
//desc: [
//{ required: true, message: '请填写活动形式', trigger: 'blur' }
// ]
}
};
},
methods: {
changeType(val){
this.changeValue=val
},
//保存
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
//调接口...
} else {
console.log('error submit!!');
return false;
}
});
},
//取消
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>