【vue】element-plus日期时间范围禁用规则

@/hooks/dateDisabled.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { ref } from "vue";

/**
* 日期选择器 日期选择禁用
*/
export function dateDisabled() {
const firstSelectDate = ref(0);
const countDay = 7;

/**
* 日历上禁用日期(禁用规则:不允许选择当天以后的日期,范围只能选择第一次选择日期的前后7天)
* @param date
* @returns {boolean}
*/
function disabledDateRange(date) {
if (firstSelectDate.value) {
// 1天毫秒时间戳
const timeRange = 24 * 60 * 60 * 1000;
const currentTime = new Date().getTime();
const minTime = firstSelectDate.value - timeRange * countDay;
let maxTime = firstSelectDate.value + timeRange * (countDay - 1);
// 如果最大时间超过当前时间处理
if (maxTime > currentTime) maxTime = currentTime;
return date.getTime() <= minTime || date.getTime() > maxTime;
} else {
return date.getTime() > new Date().getTime();
}
}

/**
* 在日历所选日期更改时触发
* @param {Array<Date>} dates
*/
function calendarChange(dates) {
firstSelectDate.value = dates[0].getTime();
if (dates[1]) firstSelectDate.value = 0;
}
return {
disabledDateRange,
calendarChange,
};
}

xxx.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<el-form-item label="日期" prop="date">
<el-date-picker
v-model="queryParams.date"
type="daterange"
value-format="YYYY-MM-DD"
range-separator="-"
start-placeholder="开始日期"
end-placeholder="结束日期"
:clearable="false"
:disabled-date="disabledDateRange"
@calendarChange="calendarChange"
></el-date-picker>
</el-form-item>
</template>

<script setup>
import { dateDisabled } from "@/hooks/dateDisabled.js";

const { disabledDateRange, calendarChange } = dateDisabled();
</script>