相关文档
业务需求
设置两个时间选择框,一个是开始时间,一个是结束时间,两者相互制约,开始不能早于结束,结束不能小于开始
代码示例
1.html
<a-form-item label="生效日期">
<date-time-picker @change="getPolicyStartTime"
:format="dateFormat"
:disabled-date="disabledBeginDate"
:value="policyStartTimeValue"
:show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
:placeholder="请选择生效日期"></date-time-picker>
</a-form-item>
<a-form-item label="到期日期">
<date-time-picker @change="getPolicyEndTime"
:format="dateFormat"
:value="policyEndTimeValue"
:show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
:disabled-date="disabledEndDate"
:placeholder="请选择到期日期"></date-time-picker>
</a-form-item>
2.js
<script lang="ts">
import moment from 'moment';
export default class Staff extends Vue {
moment = moment;
dateFormat = 'YYYY-MM-DD';
policyStartTime: any = null;
policyEndTime: any = null;
get policyStartTimeValue() {
const policyStartTime = this.policyStartTime;
return policyStartTime ? moment(this.policyStartTime) : null;
}
get policyEndTimeValue() {
const policyEndTime = this.policyEndTime;
return policyEndTime ? moment(this.policyEndTime) : null;
}
}
getPolicyStartTime(e: any) {
this.policyStartTime = e?.valueOf() ?? null;
}
getPolicyEndTime(e: any) {
this.policyEndTime = e?.valueOf() ?? null;
}
disabledBeginDate(beginDate: any) {
const endDate = this.policyEndTime;
if (!beginDate || !endDate) {
return false;
}
return beginDate > endDate;
}
disabledEndDate(endDate: any) {
const beginDate = this.policyStartTime;
if (!endDate || !beginDate) {
return false;
}
return beginDate >= endDate;
}
</script>
3. 总结
主要问题是,日期选择需要的是moment
的数据,传递给后台是时间戳
的格式
所以通过计算属性
把时间戳转化成moment数据,用于前端页面展示
在触发事件
中把moment数据转化为时间戳储存,用于与后端进行数据传递
限制关系可以通过组件的disabled-date
属性,编写对应函数传入即可