vue+el使用日期組件限制開始、結束日期選擇範圍

前言

記錄一下最近使用element UI中的DatePicker,限制開始日期不能選擇結束日期之後的日期,同樣結束日期不能選擇開始日期之前的日期。

具體實現

原理是利用DatePicker的:picker-options實現。

  1. 標籤添加:picker-options屬性
<el-form-item label="開始日期" prop="startDate">
	 <el-date-picker
	 	ref="startDate"
	    v-model="qryTableDate.startDate"
	    :picker-options="pickerOptionsStart"
	    type="date"
	    format="yyyyMMdd"
	    value-format="yyyyMMdd">
</el-form-item>
<el-form-item label="結束日期" prop="endDate">
	 <el-date-picker
	 	ref="endDate"
	    v-model="qryTableDate.endDate"
	    :picker-options="pickerOptionsEnd"
	    type="date"
	    format="yyyyMMdd"
	    value-format="yyyyMMdd">
</el-form-item>
  1. return中添加變量
data() {
	return {
		...
		pickerOptionStart: this.startDateFun(),
		pickerOptionEnd: this.endDateFun(),
		...
	}
}
  1. methods中添加具體方法
startDateFun() {
	const self = this
	return {
		disabledDate(time) {
			let end = this.qryTableDate.endDate
			if(end) {
				end = end.substring(0,4) + '-' + end.substring(4,6) + '-' +end.substring(6,8)
				return time.getTime() > new Date(end).getTime()
			}
		}
	}
},
endDateFun() {
	const self = this
	return {
		disabledDate(time) {
			let start= this.qryTableDate.startDate
			if(start) {
				start= start.substring(0,4) + '-' + start.substring(4,6) + '-' +start.substring(6,8)
				return time.getTime() < new Date(end).getTime() - 24 * 60 * 60 * 1000
			}
		}
	}
},

後記

有兩個地方需要注意,一個是時間格式如果是yyyyMMdd,需要轉換成yyyy-MM-dd,因爲new Date()不接收yyyyMMdd。另一個是結束日期要減一天,即24 * 60 * 60 * 1000,不然開始和結束日期不能選擇同一天。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章