- 需求:element-plus实现日期时间组件禁用当前日期以及小时和分钟,效果如下:
<template>
<div>
<el-date-picker
v-model="testValue"
type="datetime"
placeholder="结束时间"
value-format="YYYY-MM-DD HH:mm"
format="YYYY-MM-DD HH:mm"
:disabled-date="disabledDate"
:disabled-hours="disabledHours"
:disabled-minutes="disabledMinutes"
@update:modelValue="handleDateChange"
/>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const testValue = ref('');
const sendTime = ref(new Date());
const selectTimes = ref();
const handleDateChange = (value: any) => {
if (value && value.split(' ') && value.split(' ').length > 0) {
const parts = value.split(' ');
const datePart = parts[0];
const dateParts = datePart.split('-');
const year = dateParts[0];
const month = parseInt(dateParts[1], 10);
const day = parseInt(dateParts[2], 10);
selectTimes.value = year + '-' + month + '-' + day;
}
};
const disabledDate = (time: any) => {
const now = new Date();
return time.getTime() > now.getTime();
};
const disabledHours = () => {
const now = new Date();
const hours = now.getHours();
const disabled = [];
if (selectTimes.value && selectTimes.value.split('-') && selectTimes.value.split('-').length > 2) {
if (
selectTimes.value.split('-')[0] == now.getFullYear() &&
selectTimes.value.split('-')[1] == now.getMonth() + 1 &&
selectTimes.value.split('-')[2] == now.getDate()
) {
if (sendTime.value.getDate() === now.getDate()) {
for (let i = hours + 1; i < 24; i++) {
disabled.push(i);
}
}
return disabled;
}
}
};
const disabledMinutes = (hour: any) => {
const now = new Date();
const minutes = now.getMinutes();
const disabled = [];
if (sendTime.value.getDate() === now.getDate() && hour === now.getHours()) {
for (let i = minutes + 1; i < 60; i++) {
disabled.push(i);
}
}
return disabled;
};
</script>
<style scoped></style>