ElementUI 之 DatePicker 月份选择限制范围 disabledDate

668

1 错误写法

  1. 开始的时候是这样写的,没有考虑到月份的时候,disabledDate里面的time是日期类型的,所以在选择6个月的时候,选择到了,下来框没有消失,也就是判断sixMonth 判断是true, sixMonth这个值就是当前日期的6个月前的今天,而不是1号
<el-date-picker v-model="date" type="monthrange" :pickerOptions="pickerOptions" range-separator="至"
  start-placeholder="开始月份" end-placeholder="结束月份">
</el-date-picker>
pickerOptions: {
      // 包含当月
      disabledDate: time => {
        const sixMonth = new Date().setMonth(new Date().getMonth() - 5)
        return time.getTime() > Date.now() || time.getTime() < sixMonth
      }
    }

image.png

2. 正确写法

需要将这个最小值设为当月的第一天,这样判断才生效

 pickerOptions: {
      // 包含当月
      disabledDate: time => {
        const sixMonth = moment()
          .subtract(5, 'months')
          .startOf('month')
          .valueOf()
        return time.getTime() > Date.now() || time.getTime() < sixMonth
      }
    }