el-date-picker不可跨月的限制

317 阅读1分钟

随手记录 以便日后再次开发遇到 到时照抄就可以啦哈哈哈哈哈哈哈哈哈哈 html


<el-date-picker
              v-model="form.dateRangeValue"
              :clearable="true"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              class="label-input"
              size="medium"
              :picker-options="pickerOptionsMonth"
            >
            </el-date-picker>

1、不可跨月 禁止选择

data(){
    return{
        pickerOptionsMonth: {
       
        onPick: ({ maxDate, minDate }) => {
          this.selectTime = minDate.getTime();
          if (maxDate) {
            this.selectTime = "";
          }
        },
        disabledDate: (time) => {
          let nowDay = new Date();
          nowDay.setHours(23); //设置小时
          nowDay.setMinutes(59); //设置分钟
          nowDay.setSeconds(59); //设置秒
          nowDay.setMilliseconds(59); //设置毫妙
          let timestamp = nowDay.getTime(); //获取时间戳
          if (this.selectTime !== "") {
            const selectDate = new Date(this.selectTime);
            const nowYear = selectDate.getFullYear(); // 当前年
            const nowMonth = selectDate.getMonth(); // 当前月
            const monthStartDate = new Date(nowYear, nowMonth, 1).getTime();
            const monthEndDate = new Date(nowYear, nowMonth + 1, 0).getTime();
            return (
              time.getTime() >= timestamp ||
              time.getTime() < monthStartDate ||
              time.getTime() > monthEndDate
            );
          } else {
            return time.getTime() >= timestamp;
          }
        },
      },
    }
}
 

2、只可选一年内的时间 禁用当前时间之后选项

data(){
    return{
         pickerOptionsMonth: {
        //一年内的日期
        onPick: this.getPickDate,
        disabledDate: this.disabledDate,
      },
    }
}
methods:{
    getPickDate(pick) {
      this.pickDate = pick;
    },
    disabledDate(date) {
      const { minDate, maxDate } = this.pickDate;
      if (minDate && !maxDate) {
        const diff = Math.abs(minDate.valueOf() - date.valueOf());
        if (diff > 1000 * 3600 * 24 * 365) {
          return true;
        }
      }
      return date.getTime() > Date.now();
    },
    
}