<template>
<el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
<el-form-item label="活动区域" prop="region">
<el-select v-model="form.region" placeholder="请选择活动区域" @change="handleRegionChange">
<el-option label="区域一" value="shanghai" />
<el-option label="区域二" value="beijing" />
</el-select>
</el-form-item>
<el-form-item label="活动形式" prop="desc" :rules="descRule">
<el-input v-model="form.desc" type="textarea" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">立即创建</el-button>
<el-button @click="resetForm">重置</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
data() {
return {
form: {
region: '',
desc: ''
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
region: [
{ required: true, message: '请选择活动区域', trigger: 'change' }
],
// 其他静态验证规则
},
descRule: [] // 初始时不设为必填
}
},
watch: {
'form.region'(newValue) {
this.handleRegionChange(newValue);
}
},
methods: {
handleRegionChange(region) {
// 根据 region 的值动态设置 desc 字段的验证规则
if (region === 'shanghai') {
this.descRule = [
{ required: true, message: '请填写活动形式', trigger: 'blur' }
]
} else {
this.descRule = [] // 或其他非必填的验证规则
}
},
submitForm() {
this.$refs.formRef.validate((valid) => {
if (valid) {
alert('submit!')
} else {
console.log('error submit!!')
return false
}
})
},
resetForm() {
this.$refs.formRef.resetFields()
// 重置 descRule 到初始状态
this.descRule = []
}
},
mounted() {
// 初始化时调用一次 handleRegionChange 以确保初始验证规则正确
this.handleRegionChange(this.form.region);
}
}
</script>
根据 region 的值动态设置字段的验证规则
最新推荐文章于 2024-09-10 11:56:39 发布