ElementUI是饿了么推出的一套基于vue2.x的一个ui框架。官方文档也很详细,这里做一个element-ui日期插件的补充。
最近做项目用到了datepicker,需要对日期选择做一些限制,
以下情景:选择的时间范围最多为一年,而且只能选择当前日期之前的,2016-01-01之后的日期,代码如下:
data() { return { type: 2, dateRange: [], pickerMinDate: '', pickerOptions: { onPick: ({ maxDate, minDate }) => { console.log('maxDate=' + maxDate); console.log('minDate=' + minDate); this.pickerMinDate = minDate; }, disabledDate: (time) => { if (this.pickerMinDate !== '') { let maxTime = new CDate(this.pickerMinDate).addYear(1); if (maxTime > new Date()) { maxTime = new Date(); } return time.getTime() > maxTime.getTime() || time.getTime() > Date.now() - 8.64e6; } else { return time.getTime() <= new Date('2016-01-01').getTime() || time.getTime() > Date.now() - 8.64e6; } } } }; },
刚开始用time.getTime()>Date.now(),怎么也选择不了今天的日期,后来改成以下才可以
time.getTime() > Date.now() - 8.64e6;
以下代码为参考:
单个输入框:
<el-date-picker
v-model="value1"
type="date"
placeholder="选择日期"
:picker-options="pickerOptions0">
</el-date-picker>
情景1: 设置选择今天以及今天之后的日期
data (){
return {
pickerOptions0: {
disabledDate(time) {
return time.getTime() < Date.now() - 8.64e7;
}
},
}
}
情景2: 设置选择今天以及今天以前的日期
data (){
return {
pickerOptions0: {
disabledDate(time) {
return time.getTime() > Date.now() - 8.64e6
}
},
}
}
情景3: 设置选择今天之后的日期(不能选择当天时间)、
data (){ return { pickerOptions0: { disabledDate(time) { return time.getTime() < Date.now(); } }, } }
情景4: 设置选择今天之前的日期(不能选择当天)
data (){ return { pickerOptions0: { disabledDate(time) { return time.getTime() > Date.now(); } }, } }
情景5: 设置选择三个月之前到今天的日期
data (){
return {
pickerOptions0: {
disabledDate(time) {
let curDate = (new Date()).getTime();
let three = 90 * 24 * 3600 * 1000;
let threeMonths = curDate - three;
return time.getTime() > Date.now() || time.getTime() < threeMonths;;
}
},
}
}
两个输入框
组件代码
<el-date-picker
v-model="value1"
type="date"
placeholder="开始日期"
:picker-options="pickerOptions0">
</el-date-picker>
<el-date-picker
v-model="value2"
type="date"
placeholder="结束日期"
:picker-options="pickerOptions1">
</el-date-picker>
情景1: 限制结束日期不能大于开始日期
data(){
return {
pickerOptions0: {
disabledDate: (time) => {
if (this.value2 != "") {
return time.getTime() > Date.now() || time.getTime() > this.value2;
} else {
return time.getTime() > Date.now();
}
}
},
pickerOptions1: {
disabledDate: (time) => {
return time.getTime() < this.value1 || time.getTime() > Date.now();
}
},
}
}
针对选择范围(type="daterange")的日期筛选,类似于单个输入框的情况,直接使用参数time进行判断
参考链接:https://www.cnblogs.com/xjcjcsy/p/7977966.html