情景描述:
el-form 的ref="obj" rules 对象obj有a,b,c三个字段,点击按钮a,a和b字段必填,点击按钮c,c字段必填,如何通过 this.$refs.obj.validate((valid)=>{})去判断呢
javascript
<template>
<div>
<!-- 你的表单组件 -->
<el-form ref="obj" :model="obj" :rules="updatedRules">
<!-- 表单字段 -->
<el-form-item prop="a" label="字段 a">
<el-input v-model="obj.a"></el-input>
</el-form-item>
<el-form-item prop="b" label="字段 b">
<el-input v-model="obj.b"></el-input>
</el-form-item>
<el-form-item prop="c" label="字段 c">
<el-input v-model="obj.c"></el-input>
</el-form-item>
<el-button type="primary" @click="submitFormAB('obj')">Submit</el-button>
<el-button type="primary" @click="submitFormC('obj')">Submit</el-button>
</el-form>
</div>
</template>
<script>
export default {
data(){
return {
updatedRules:{}
}
},
watch: {
updatedRules: {
handler(newVal, oldVal) {
// 如果需要,可以在这里处理 rules 变化的逻辑
console.log('Rules 发生变化:', newVal);
},
immediate: true // 组件挂载时立即触发
}
},
methods:{
submitFormAB(formData){
this.$nextTick(() => { //这里注意使用了 $nextTick 以便于渲染dom
// 动态更新验证规则后重置表单验证状态
this.$refs[formData].clearValidate();
// 更新完规则后执行验证--备注一下代码
// this.$refs.obj.validate();
});
this.updatedRules = {
a: [{ required: true, message: '字段 a 必填', trigger: 'blur' }],
b: [{ required: true, message: '字段 b 必填', trigger: 'blur' }]
};
this.$resf[formData].validate((valid)=>{
if(valid){
//验证完之后调接口
}
})
},
submitFormC(formData){
this.$nextTick(() => {
// 动态更新验证规则后重置表单验证状态
this.$refs[formData].clearValidate();
});
this.updatedRules = {
c: [{ required: true, message: '字段 c 必填', trigger: 'blur' }]
};
this.$resf[formData].validate((valid)=>{
if(valid){
//验证完之后调接口
}
})
},
}
};
</script>