碰到个需求是在日期范围中,需要根据用户选择一个日期后动态的进行限制只能选择前后一个礼拜
一、 根据文档利用el-date-picker组件自带的pickerOptions属性可以完成这个需求,代码如下:
<el-date-picker
@blur="blurDate"
v-model="form.dateArr"
type="daterange"
range-separator="-"
value-format="yyyy-MM-dd"
:pickerOptions="timeOption"
start-placeholder="开始日期"
end-placeholder="结束日期">
</el-date-picker>
data() {
return {
timeOption: {
onPick: ({ maxDate, minDate }) => {
this.minDate = minDate
this.maxDate = maxDate
},
disabledDate: (time) => {
if (this.minDate && !this.maxDate) {
const range = 6 * 24 * 3600 * 1000
const minTime = this.minDate.getTime()
const newTime = time.getTime()
return newTime > (minTime + range) || newTime < (minTime - range)
}
return false
}
},
minDate: '',
maxDate: ''
}
}
效果图:
但是发现还是有点问题的,当用户点击一个日期后,关闭日期选择框再打开,会发现之前禁用的日期还被禁用着,这是个小问题,解决方案:
添加一个失焦事件,当失焦时清除选中的日期: 在el-date-picker标签中添加 @blur=“blurDate”,然后在methods中定义方法:
<el-date-picker
@blur="blurDate"
</el-date-picker>
methods:{
blurDate() {
this.minDate = ''
},
}
二、补充 (日期控件其他控制禁用日期方法)
- 只能选择当前月份之前或者之后的月份
<el-date-picker
v-model="formData.month"
:pickerOptions="timeOption"
type="monthrange"
range-separator="-"
start-placeholder="开始月份"
end-placeholder="结束月份" value-format="yyyy-MM">
</el-date-picker>
data() {
return {
timeOption: {
disabledDate: (time) => {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
if (month >= 1 && month <= 9) {
month = "0" + month;
}
var currentdate = year.toString() + month.toString();
var timeyear = time.getFullYear();
var timemonth = time.getMonth() + 1;
if (timemonth >= 1 && timemonth <= 9) {
timemonth = "0" + timemonth;
}
var timedate = timeyear.toString() + timemonth.toString();
return currentdate > timedate;
}
},
}
}
- 只能选择当天日期之前的或者之后的日期
<el-date-picker
v-model="form.date"
type="daterange"
range-separator="-"
value-format="yyyy-MM-dd"
:pickerOptions="timeOption"
start-placeholder="开始日期"
end-placeholder="结束日期">
</el-date-picker>
data() {
return {
timeOption: {
disabledDate:(time)=>{
return time < new Date().now()
}
},
}
|