ElementUI 日期选择器 datepicker选择范围限制
在使用 el-date-picker 的时候,经常会对选择的时间进行一定限制,所以今天就总结了一些范围
1、第一步 给 el-date-picker 组件添加 picker-options 属性,并绑定 对应数据 pickerOptions
2、对绑定的数据进行限制
单个选择框的限制
2.1 设置今天及最近一年内的日期(包含今天)
data(){
return {
pickerOptions:{disabledDate(time){let nowDate = (new Date()).toString() // 当前时间转字符串let nowDateYear = (new Date()).getFullYear() // 当前时间的年份let oneYearAgoDate = nowDate.replace(nowDateYear,nowDateYear-1) //字符串年份替换为一年前let oneYear = new Date(oneYearAgoDate).getTime() //一年前字符串转为时间戳return time.getTime() > Date.now() || time.getTime() < oneYear}},}}
2.2 设置今天及今天之后的日期
data(){
return {
pickerOptions:{disabledDate(time){return time.getTime() < Date.now() - 8.64e7;}},}}
2.3 设置今天及今天以前的日期
data(){
return {
pickerOptions:{disabledDate(time){return time.getTime() > Date.now() - 8.64e7;}},}}
2.4 设置选择今天之后的日期(不包含当天时间)
data(){
return {
pickerOptions:{disabledDate(time){return time.getTime() < Date.now();}},}}
2.5 选择今天之前的时间(不包含当天时间)
data(){
return {
pickerOptions:{disabledDate(time){return time.getTime() > Date.now();}},}}
2.6 设置选择三个月之前到今天的日期
data(){
return {
pickerOptions:{disabledDate(time){let nowDate = (new Date()).getTime();let three = 90*24*3600*1000;let threeMonths = nowDate - three;return time.getTime() > Date.now() || time.getTime() < threeMonths}},}}
两个日期选择框的限制
3.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();}}}
}
3.2 设置开始时间不能大于结束时间(可以选择所有日期)
data(){return {pickerOptions0: {disabledDate: (time) => {if (this.value2) {return time.getTime() > this.searchForm.endTime}}},pickerOptions1: {disabledDate: (time) => {return time.getTime() < this.searchForm.startTime}}}
}