ant-design-vue 实现日期选择器选择必须大于今天
2023-03-28 本文已影响0人
枸杞辣条
现需要一个选择器,只能选择当前时间之后的
前置需要了解 dayjs 的API:
https://day.js.org/docs/en/manipulate/start-of#docsNav
https://day.js.org/docs/en/query/is-same#docsNav
<template>
<a-space direction="vertical">
<a-date-picker
v-model:value="value1"
format="YYYY-MM-DD HH:mm:ss"
:disabled-date="disabledDate"
:disabled-time="disabledDateTime"
:show-time="{ defaultValue: dayjs() }"
/>
</a-space>
</template>
<script>
import dayjs from "dayjs";
import { defineComponent, ref } from "vue";
export default defineComponent({
setup() {
const range = (start, end) => {
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
};
const disabledDate = (current) => {
// Can not select days before today and today
return current && current < dayjs().startOf("day");
};
const disabledDateTime = (d) => {
let curDate = d || dayjs();
let now = dayjs();
const isSameDay = curDate.isSame(now, "day");
const isSameHour = curDate.isSame(now, "hour");
const isSameMinute = curDate.isSame(now, "minute");
return {
disabledHours: () => {
if (isSameDay) {
return range(0, now.hour());
}
},
disabledMinutes: () => {
if (isSameHour) {
return range(0, now.minute());
}
},
disabledSeconds: () => {
if (isSameMinute) {
return range(0, now.second());
}
},
};
};
return {
dayjs,
value1: ref(),
disabledDate,
disabledDateTime,
};
},
});
</script>
需要考虑的问题
1. 如何disabledDate
dayjs().startOf("day")
当前最开始的时间
const disabledDate = (current) => {
// 日期判断会比较简单
return current && current < dayjs().startOf("day");
};
2. 比较复杂的是如何禁止选时间控件大于今天,这个是比较有讲究的
// 判断时间会比较复杂,要考虑时分秒
// d有可能是null | Dayjs,每次选择日期d都会改变
// 这里写了一个range的构造函数
const disabledDateTime = (d) => {
let curDate = d || dayjs();
let now = dayjs();
const isSameDay = curDate.isSame(now, "day");
const isSameHour = curDate.isSame(now, "hour");
const isSameMinute = curDate.isSame(now, "minute");
return {
disabledHours: () => {
if (isSameDay) {
return range(0, now.hour());
}
},
disabledMinutes: () => {
if (isSameHour) {
return range(0, now.minute());
}
},
disabledSeconds: () => {
if (isSameMinute) {
return range(0, now.second());
}
},
};
};
isSameDay
用来判断是否是当天,如果是当天,时的控件不能选择当前时之前,如果是当天当时isSameHour
,则当前不可选当前分之前,如果是当天当时当分isSameMinute
,则限制秒不可选now之前的秒。
结尾
以上适用于ant-design。