问题:选择switch 改变 ruleForm.delivery 的值,动态实现校验生效
vue代码:
<template>
<div id="app">
<el-form
:model="ruleForm"
:rules="rules"
ref="ruleForm"
label-width="100px">
<el-form-item label="切换" prop="delivery">
<el-switch v-model="ruleForm.delivery"></el-switch>
</el-form-item>
<el-form-item
label="text"
prop="desc"
:required="ruleForm.delivery ? true : false">
<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-form-item>
</el-form>
</div>
</template>
<script>
export default {
data() {
let test = (rule, value, callback) => {
if (!value && this.ruleForm.delivery) {
callback(new Error("不能为空"));
} else {
callback();
}
};
return {
ruleForm: {
delivery: false,
desc: "",
},
rules: {
desc: [{ trigger: "blur", validator: test }],
},
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert("submit!");
} else {
console.log("error submit!!");
return false;
}
});
},
},
};
</script>
let test = (rule, value, callback) 验证规则函数要在定义 rules 之前