一个基于vue3+javascript+elementPlus+dayjs 实现 日期时间选择器(datetime)并禁用未来时间(到时分秒)
一定要注意elementPlus版本问题 ,十分重要!!!
本地版本是"element-plus": “^2.10.3”
拆箱即用版 话不多说,直接上代码
<template>
<div class="block">
<span class="demonstration">日期时间-type:datetime 禁止选择未来时间</span>
{{ value1 }}
<el-date-picker
v-model="value1"
type="datetime"
:disabled-date="disabledDate"
:disabled-hours="disabledHours"
:disabled-minutes="disabledMinutes"
:disabled-seconds="disabledSeconds"
placeholder="Select date and time"
/>
</div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import dayjs from "dayjs";
const value1 = ref("");
console.log("value1::", value1);
let currentDateTime = dayjs();
// 禁止选择未来日期
const disabledDate = (time) => {
return dayjs(time).isAfter(dayjs().endOf("day"));
};
// 禁止选择未来小时
const disabledHours = (role, date) => {
if (!date) return [];
if (dayjs(date).isSame(dayjs(), "day")) {
// console.log("是同一天,禁用未来小时");
const currentHour = dayjs().hour();
return Array.from(
{ length: 23 - currentHour },
(_, i) => currentHour + 1 + i
);
}
return [];
};
// 禁用未来的分钟
const disabledMinutes = (selectedHour, role, date) => {
if (!date) return [];
// 只有选择今天且选择当前小时时,才需要禁用未来的分钟
if (
dayjs(date).isSame(currentDateTime, "day") &&
selectedHour === currentDateTime.hour()
) {
const currentMinute = currentDateTime.minute();
return Array.from(
{ length: 59 - currentMinute },
(_, i) => currentMinute + 1 + i
);
}
return [];
};
// 禁用未来的秒数
const disabledSeconds = (selectedHour, selectedMinute, role, date) => {
if (!date) return [];
// 只有选择今天、当前小时且当前分钟时,才需要禁用未来的秒数
if (
dayjs(date).isSame(currentDateTime, "day") &&
selectedHour === currentDateTime.hour() &&
selectedMinute === currentDateTime.minute()
) {
const currentSecond = currentDateTime.second();
return Array.from(
{ length: 59 - currentSecond },
(_, i) => currentSecond + 1 + i
);
}
return [];
};
// range:[ "2025-09-10T16:00:00.000Z", "2025-10-14T16:00:00.000Z" ]
// datetime: Mon Sep 01 2025 00:00:00 GMT+0800 (中国标准时间)
</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>
1754

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



