应用场景1:只能选今天以后的时间
实现方法:
<template>
<el-date-picker
v-model="form.forecastDate"
@change="forecastDateChange"
:picker-options="pickerOptions"
type="date"
placeholder="选择日期"
style="width: 300px">
</el-date-picker>
</template>
<script>
export dafault{
data(){
return{
form:{
forecastDate: '',
},
pickerOptions:{
disabledDate(time){
return time.getTime() < Date.now() - 8.64e7;
}
},
}
},
}
</script>
8.64e7=246060*1000
是一天的毫秒数
disableDate里针对每一个时间返回true或false
现在方法里的意思是,如果时间小于当前时间的前一天,就返回true,即给disable掉
应用场景2:
默认今天前的日期禁用,但是如果时间A选择了,则要在时间A的前一天禁用
如下图,当需求时间为空时,后面时间是今天前的日期禁用,但是需求时间不空时,后面时间需要禁用需求时间及以前
实现方法如下:
<template>
<div>
<el-date-picker
v-model="form.forecastDate"
@change="forecastDateChange"
:picker-options="pickerOptions"
type="date"
placeholder="选择日期"
style="width: 300px">
</el-date-picker>
<el-date-picker
v-model="form.returnDate"
:picker-options="returnDatePickerOptions"
type="date"
placeholder="选择日期"
style="width: 300px"
class="mar-left10">
</el-date-picker>
</div>
</template>
<script>
export dafault{
data(){
return{
form:{
forecastDate: '',
returnDate: '',
},
pickerOptions:{
disabledDate(time){
return time.getTime() < Date.now() - 8.64e7;
}
},
returnDatePickerOptions:{
disabledDate:time=>{
const forecastDate = this.form.forecastDate
if(forecastDate == ''){
//若需求时间为空,则昨天及以前不可选
return time.getTime() < Date.now() - 8.64e7;
}else{
//若需求时间不为空,则需求时间的后一天及以后可选
return time.getTime() < new Date(forecastDate).getTime() + 8.64e7;
}
}
},
}
},
}
</script>
这里需要注意一个点,就是returnDatePickerOptions里的箭头方法。
如果还按照上面的pickerOptions,则会报错
TypeError: Cannot read properties of undefined (reading 'formData') at disabledDate
问题的原因可能是在returnDatePickerOptions的disabledDate方法中,this关键字不指向Vue实例。为了确保this正确指向Vue实例,你可以使用箭头函数来定义disabledDate方法,因为箭头函数继承了其父级的上下文