- 需求:时间选择器可选的时间范围进行限制,-2年<a<2年且a<new Date().getTime()
- 核心:这里需要注意plus版没有
picker-options
换成disabled-date
属性了,使用了visible-change和calendar-change属性
- 逻辑:另设一个参数记录第一个点击的时间点,根据这个时间点设置时间范围,使用
visible-change和calendar-change属性
来进行第一个时间点的记录和清空 - 代码环境:vue3 elementplus ts
- 效果

- 当前时间为25-2-10,且没有进行第一位的时间选择所以仅大于该日期的不能选择

- 选择了第一位时间24-2-6,所以可选时间范围为 小于该值2年内或者大于该值2年内且小于当前时间25-2-10的值,如下方几张图所示
- 小于22年2月6号的不能选

- 大于26-2-6的且大于25-2-10的不能选(我这个24年选的不太好,应该选22年就能展示了但是不想截图了哈哈,应该能理解我的意思吧)

- 代码
<el-date-pickerv-model="rightTime"type="datetimerange"range-separator="-"start-placeholder="开始时间"end-placeholder="结束时间":disabled-date="disabledDate"format="YYYY-MM-DD HH:mm:ss"value-format="YYYY-MM-DD HH:mm:ss"@visible-change="onvisibleChange"@calendar-change="oncalendarChange"/>
const rightTime = ref([])
const chooseDay= ref(null) const onvisibleChange = (val)=>{if(val){chooseDay.value = null}
}
const oncalendarChange = (val)=>{const [chooseFirstDate] = valchooseDay.value = new Date(chooseFirstDate)}const disabledDate = (time: Date) => { const now = new Date(); if (!chooseDay.value) { return time.getTime() > now.getTime() }else{ const twoYearsAgoMin = new Date(chooseDay.value.getFullYear() - 2, chooseDay.value.getMonth(), chooseDay.value.getDate());const twoYearsAgoMax = new Date(chooseDay.value.getFullYear() + 2, chooseDay.value.getMonth(), chooseDay.value.getDate());return time.getTime() > now.getTime() || time.getTime() < twoYearsAgoMin || time.getTime() > twoYearsAgoMax }}