elementui日期范围禁用问题

88 阅读1分钟

在做后台管理系统时,为了让查询速度快一点,会限制时间范围为某个时间段,比如7天内或者30天内,下面结合elementui的日期组件做一些处理

 <el-date-picker
    v-model="pageRequest.req.date"
    type="datetimerange"
    range-separator="-"
    class="date-item"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    style="width: 73%"
    :default-time="['00:00:00', '23:59:59']"
    :pickerOptions="pickerOptions"
  />

最主要的就是pickerptions属性

 data() {
     return {
         choiceDate:'',
         pickerOptions:{
             onPick: ({ maxDate, minDate }) => {
                      // 把选择的第一个日期赋值给一个变量。
                      this.choiceDate = minDate.getTime()
                      // 如果你选择了两个日期了,就把那个变量置空
                      if (maxDate) this.choiceDate = ''
              },
              disabledDate: time => {
                  // 如果选择了一个日期
                  if (this.choiceDate) {
                    // 7天的时间戳
                    const one = 6 * 24 * 3600 * 1000
                    // 当前日期 - one = 7天之前
                    const minTime = this.choiceDate - one
                    // 当前日期 + one = 7天之后
                    const maxTime = this.choiceDate + one
                    return (
                      time.getTime() < minTime || time.getTime() > maxTime
                      // 限制不能选择今天及以后
                      // || time.getTime() + 1 * 24 * 3600 * 1000 > Date.now()
                    )
                  } else {
                    // 如果没有选择日期,就要限制不能选择今天及以后
                    // return time.getTime() + 1 * 24 * 3600 * 1000 > Date.now();
                  }
                }
         }
     }
     
 }

效果:选择了8.1,结束日期最大只能选择到7号,其他时间就被禁用了

image.png