disabledDate如何灵活设置禁用状态

21 阅读2分钟

# 【element】el-date-picker限制只可以选择前后一个月时间,只能选择今年的时间,大于今天的不可选

# disabledDate如何灵活设置禁用状态

需求背景

一个日期时间范围选择器,用户可以选择任意时间点,但是时间跨度限制三个月

举例:

用户选择任意时间: 如2025-03-01, 但第二个时间最多往后选择在2025-06-01, 往前选最多选到2025-01-01

最终选择出来的时间跨度在三个月内(后端数据查询只能支持三个月跨度的数据量查询)

实现

ps:disabledDateonPick必须是箭头函数,否则this指向有问题

 <el-form-item label="日期" prop="createTime">
  <el-date-picker
    v-model="form.createTime"
    type="daterange"
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :default-time="['00:00:00', '23:59:59']"
    value-format="yyyy-MM-dd HH:mm:ss"
    style="width: 320px"
    :picker-options="pickerOptions"
    :clearable="false"
  >
  </el-date-picker>
</el-form-item>
computed:{
    pickerOptions() {
      return { 
      
        // 大时间 maxDate,小时间 minDate
        onPick: ({ maxDate, minDate }) => {
          // 选中的时间
          this.tempTime0 = minDate.getTime();
          // 第一个选择的时间都会被放在minDate里面,选择了第二个参数之后则一定会保证 maxDate, minDate 都有值
          // 当 maxDate 有值时,则说明第二个参数被选中了,此时需要清空第一个参数的值
          if (maxDate) {
            this.tempTime0 = "";
          }
          console.log("onPick", maxDate, minDate, this.tempTime0);
        },
        
        disabledDate: (time) => {
          const targetTime = this.tempTime0;
          if (!targetTime) return false;
          console.log("disabledDate", targetTime);

          // 解析目标日期
          const givenDate = moment(targetTime);
          // 计算三个月前的日期
          const threeMonthsAgo = moment(givenDate).subtract(3, "months");
          // 计算三个月后的日期
          const threeMonthsLater = moment(givenDate).add(3, "months");
          // 获取当前日期
          const now = moment();
          // 将time参数转换为moment对象
          const currentDate = moment(time);

          // 判断是否禁用
          // 1. 如果日期在三个月之前
          // 2. 如果日期在三个月之后
          // 3. 如果日期在当前日期之后
          return currentDate.isBefore(threeMonthsAgo) || currentDate.isAfter(threeMonthsLater) || currentDate.isAfter(now);
        },
      };
    },
}