element ui 日期控件設置禁止跨年,跨月

1.ELEMENT UI 日期選擇器禁止跨年選擇(禁止跨月同理)

未日期選擇時:

選擇第一個日期之後其他年份的日期無法選擇,第二個日期只能從第一個日期年份中選擇效果圖:

<el-date-picker v-model="selectedDateValue" value-format="yyyy-MM-dd" 
format="yyyy-MM-dd" type="daterange" :picker-options="pickerOptions0" 
range-separator="至" ></el-date-picker>
export default {
  data() {
    return {
      selectDate: null, 
      selectedDateValue: null, //時間區間
      pickerOptions0: {
        disabledDate: time => {
          if (this.selectDate == null) {
            return false
          } else {
            return (this.selectDate.getFullYear() != time.getFullYear())
          }
        },
        onPick: date => {
          // 如果只選擇一個則保存至selectDate 否則selectDate 爲空
          if (date.minDate && !date.maxDate) {
            this.selectDate = date.minDate
          } else {
            this.selectDate = null
          }
        }
      },
    };
  },
}

2.ElementUI日期組件el-date-picker設置不能跨年/跨月/跨周

<el-date-picker
    v-model="groupSearchTime"
    type="daterange"
    range-separator="至"
    start-placeholder="開始日期"
    end-placeholder="結束日期"
    value-format="yyyy-MM-dd"
    style="width: 482px;line-height: 24px"
    :picker-options="pickerOptions"
    @change="getSearchTime">
</el-date-picker>

data中的代碼:通過pickerOptions字段來控制時間選擇器組件的禁用與否,因此關鍵點就在於得到合法時間的前後時間

data() {
    return {
      groupSearchTime: [],
      choiceDate: '',
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate = minDate.getTime()
          if (maxDate) {
            this.choiceDate = ''
          }
        },
        disabledDate: (time) => {
          const self = this
          if (self.choiceDate) {
            const selectDate = new Date(self.choiceDate)
            const nowYear = selectDate.getFullYear() // 當前年
            const nowMonth = selectDate.getMonth() // 當前月
            const nowDate = selectDate.getDate() // 當前幾號
            const nowDay = selectDate.getDay() // 當前星期幾
            // 本月的開始時間
            const monthStartDate = new Date(nowYear, nowMonth, 1).getTime()
            // 本月的結束時間
            const monthEndDate = new Date(nowYear, nowMonth + 1, 0).getTime()
            // 本年的開始時間
            const yearStartDate = new Date(nowYear, 0, 1).getTime()
            // 本年的結束時間
            const yearEndDate = new Date(nowYear, 12, 0).getTime()
            // 本週的開始時間,本週的結束時間
            const weekStartDate = new Date(nowYear, nowMonth, nowDate - nowDay + 1)
            const weekEndDate = new Date(nowYear, nowMonth, nowDate + (7 - nowDay))
            // 前後三天
            const tStartDate = new Date(nowYear, nowMonth, nowDate - 2)
            const tEndDate = new Date(nowYear, nowMonth, nowDate + 2)
            // 此處以不能跨月做示範
            return time.getTime() < monthStartDate || time.getTime() > monthEndDate
          }
        }
      }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章