一个基于vue3+javascript+elementPlus+dayjs 实现 日期时间选择器并禁用未来时间(到时分秒)
一定要注意elementPlus版本问题 ,十分重要!!!
本地版本是"element-plus": “^2.10.3”
话不多说,直接上代码
<template><div class="demo-datetime-picker">
<div class="block">
<span class="demonstration"
>日期时间-type:datetimerange 禁止选择未来时间</span
>
<el-date-picker
v-model="datetimerange"
type="datetimerange"
range-separator="至"
start-placeholder="开始时间"
end-placeholder="结束时间"
:disabled-date="disabledDate"
:disabled-hours="disabledHours"
:disabled-minutes="disabledMinutes"
:disabled-seconds="disabledSeconds"
/>
</div>
</div>
</template>
<script lang="ts" setup>
import { ref, computed } from "vue";
import dayjs from "dayjs";
const now = computed(() => {
return dayjs();
});
const datetimerange = ref([]);
// 获取当前角色对应的时间值
const getTargetTime = (role) => {
return role === "start" ? datetimerange.value[0] : datetimerange.value[1];
};
// 检查是否为当天
const isToday = (role) => {
const targetValue = getTargetTime(role);
return targetValue ? dayjs(targetValue).isSame(dayjs(), "day") : false;
};
// 检查是否为当前小时
const isCurrentHour = (hour, role) => {
const targetValue = getTargetTime(role);
return targetValue
? dayjs(targetValue).hour() === hour &&
dayjs(targetValue).hour() === dayjs().hour()
: false;
};
// 禁止选择未来日期
const disabledDate = (time) => {
return dayjs(time).isAfter(dayjs().endOf("day"));
};
// 禁止选择未来小时
const disabledHours = (role) => {
if (!isToday(role)) return [];
const currentHour = now.value.hour();
return Array.from(
{ length: 23 - currentHour },
(_, i) => currentHour + 1 + i
);
};
// 禁止选择当前小时后的分钟
const disabledMinutes = (selectedHour, role) => {
// 不是当天或不是当前小时,不禁用分钟
if (!isToday(role) || !isCurrentHour(selectedHour, role)) return [];
const currentMinute = now.value.minute();
return Array.from(
{ length: 59 - currentMinute },
(_, i) => currentMinute + 1 + i
);
};
// 禁止选择当前分钟后的秒
const disabledSeconds = (selectedHour, selectedMinute, role) => {
if (!isToday(role) || !isCurrentHour(selectedHour, role)) return [];
if (selectedMinute !== now.value.minute()) return [];
const currentSecond = now.value.second();
return Array.from(
{ length: 59 - currentSecond },
(_, i) => currentSecond + 1 + i
);
};
</script>
<style scoped>
.block {
padding: 30px 0;
text-align: center;
border-right: solid 1px var(--el-border-color);
flex: 1;
}
.block:last-child {
border-right: none;
}
.block .demonstration {
display: block;
color: var(--el-text-color-secondary);
font-size: 14px;
margin-bottom: 20px;
}
</style>
1024

被折叠的 条评论
为什么被折叠?



