Element's date picker el-date-picker separate date constraints

elementUI comes with a lot of date selection components, but there are always some needs that cannot meet us developers. The requirement I encountered is that the activity time cannot be written in one piece, like this:
Insert picture description here
For this, I can only use two components to piece together into a separate choice of "start time" and "end time", but the end time and the start time The choice is subject to certain constraints. For example: the past time cannot be selected, and the end time needs to be greater than the start time. After many attempts, I chose two el-date-picker components to complete the requirements and meet the time limit. Not much to say, code!


<el-date-picker 
	v-model="form.beginTime" 
	type="datetime" 
	placeholder="起始时间" 
	:picker-options="startDatePicker" 
	:disabled="isEdit" 
	@blur="blur0" 
	@focus="focus0"
/>
<span></span>
<el-date-picker 
	v-model="form.endTime" 
	type="datetime" 
	placeholder="结束时间" 
	:picker-options="endDatePicker"
	@blur="blur1" 
	@focus="focus1" 
/>

data(
return{
    
    
	startDatePicker: this.beginDate(),
	endDatePicker: this.processDate(),
	}
)
//这里面有个小坑,在这之前我是直接写方法,在data里面是不可以互相取值的
//比如
data(
return{
    
    
	aa:9,
	b:this.aa+1//这句是报错的,这里获取不到a变量
}
)
//所以上面直接用this.beginDate()方法来避免这个问题,这样直接用方法返回时间选择的限制,beginDate()方法就在methods上写

//methods部分
beginDate() {
    
    
	const that = this;
	return {
    
    
		disabledDate(time) {
    
    
			if (that.form.endTime) {
    
    
				console.log(new Date(that.form.endTime).getTime())
				//如果结束时间不为空,则小于结束时间
				return (
					time.getTime() > new Date(that.form.endTime).getTime() || time.getTime() <  new Date().getTime()
				);
			} else {
    
    
				return time.getTime() < new Date().getTime()
			}
		}
	}
},
processDate() {
    
    
	const that = this;
	return {
    
    
		disabledDate(time) {
    
    
			if (that.form.beginTime) {
    
    
				//如果开始时间不为空,则结束时间大于开始时间
				return (
					time.getTime() < new Date(that.form.beginTime).getTime()
				);
			} else {
    
    
				return time.getTime() < new Date().getTime()//开始时间不选时,结束时间最大值小于等于当天
			}
		}
	}
},
disabledDate()方法是element的方法,它返回一个Boolean值,可以设置日期范围的禁止选择状态

Insert picture description here
Realized effect diagram: When the
Insert picture description here
end time is not selected, the start time can be selected from the current time to the present. After the end time is selected, the start time can only be selected from the current time to the end time.

Get it done! Here is the time for praise...Thank you, everyone.

Guess you like

Origin blog.csdn.net/Smell_rookie/article/details/102408163
Recommended