- 主要关注点在于校验的方式:
<div class="timeChangeItem">
<lc-form ref="vulnTime" :rules="ruleValidate" :model="vulnTime" >
<lc-form-item :required='true' label='有效时间:' prop='scopeTime'
:rules="[{ type: 'array', required: true,
fields: {
0: { type: 'date', required: true, message: '请选择有效时间' },
1: { type: 'date', required: true, message: '请选择有效时间' },
} }]">
<lc-date-picker
type="datetimerange"
format="yyyy-MM-dd HH:mm:ss"
valueFormat="yyyy-MM-dd HH:mm:ss"
v-model="vulnTime.scopeTime"
@on-change="handleTimeChange"
placeholder="开始时间 -结束时间"
style="width: 300px">
</lc-date-picker>
</lc-form-item>
</lc-form>
</div>
<script>
data:{
return{
vulnTime:{
scopeTime:'',
}
}
},
methods:{
handleTimeChange() {
if (startTime && endTime) {
this.vulnTime.scopeTime = [
moment(this.vulnTime.scopeTime[0]).format('YYYY-MM-DD HH:mm:ss'),
moment(this.vulnTime.scopeTime[1]).format('YYYY-MM-DD HH:mm:ss'),
];
} else {
this.vulnTime.scopeTime = [];
}
},
}
}
</script>
-
这样的校验方式会导致时间组件框一直处于提交状态,无法正常通过校验;
-
校验改正:自定义validator方法进行校验;
<div class="timeChangeItem">
<lc-form-item :required='true' label='有效时间:' prop='scopeTime'>
<lc-date-picker
type="datetimerange"
format="yyyy-MM-dd HH:mm:ss"
valueFormat="yyyy-MM-dd HH:mm:ss"
v-model="vulnTime.scopeTime"
@on-change="handleValidDateChange"
placeholder="开始时间 -结束时间"
style="width: 300px">
</lc-date-picker>
</lc-form-item>
</div>
<script>
data:{
const validTimeRange = (rule, value, callback) => {
if (!this.vulnTime.scopeTime[0] && !this.vulnTime.scopeTime[1]) {
callback(new Error('请输入有效时间'));
} else {
callback();
}
};
return{
vulnTime:{
scopeTime:'',
},
ruleValidate: {
scopeTime: [
{ validator: validTimeRange },
],
},
}
},
methods:{
handleTimeChange() {
if (startTime && endTime) {
this.vulnTime.scopeTime = [
moment(this.vulnTime.scopeTime[0]).format('YYYY-MM-DD HH:mm:ss'),
moment(this.vulnTime.scopeTime[1]).format('YYYY-MM-DD HH:mm:ss'),
];
} else {
this.vulnTime.scopeTime = [];
}
},
}
</script>
- 记录一下觉得思路