element ui 日期控件设置禁止跨年,跨月
1.ELEMENT UI 日期选择器禁止跨年选择(禁止跨月同理)
未日期选择时:
选择第一个日期之后其他年份的日期无法选择,第二个日期只能从第一个日期年份中选择效果图:
<el-date-picker v-model="selectedDateValue" value-format="yyyy-MM-dd"
format="yyyy-MM-dd" type="daterange" :picker-options="pickerOptions0"
range-separator="至" ></el-date-picker>
export default {
data() {
return {
selectDate: null,
selectedDateValue: null, //时间区间
pickerOptions0: {
disabledDate: time => {
if (this.selectDate == null) {
return false
} else {
return (this.selectDate.getFullYear() != time.getFullYear())
}
},
onPick: date => {
// 如果只选择一个则保存至selectDate 否则selectDate 为空
if (date.minDate && !date.maxDate) {
this.selectDate = date.minDate
} else {
this.selectDate = null
}
}
},
};
},
}
2.ElementUI日期组件el-date-picker设置不能跨年/跨月/跨周
<el-date-picker
v-model="groupSearchTime"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="yyyy-MM-dd"
style="width: 482px;line-height: 24px"
:picker-options="pickerOptions"
@change="getSearchTime">
</el-date-picker>
data中的代码:通过pickerOptions字段来控制时间选择器组件的禁用与否,因此关键点就在于得到合法时间的前后时间
data() {
return {
groupSearchTime: [],
choiceDate: '',
pickerOptions: {
onPick: ({ maxDate, minDate }) => {
this.choiceDate = minDate.getTime()
if (maxDate) {
this.choiceDate = ''
}
},
disabledDate: (time) => {
const self = this
if (self.choiceDate) {
const selectDate = new Date(self.choiceDate)
const nowYear = selectDate.getFullYear() // 当前年
const nowMonth = selectDate.getMonth() // 当前月
const nowDate = selectDate.getDate() // 当前几号
const nowDay = selectDate.getDay() // 当前星期几
// 本月的开始时间
const monthStartDate = new Date(nowYear, nowMonth, 1).getTime()
// 本月的结束时间
const monthEndDate = new Date(nowYear, nowMonth + 1, 0).getTime()
// 本年的开始时间
const yearStartDate = new Date(nowYear, 0, 1).getTime()
// 本年的结束时间
const yearEndDate = new Date(nowYear, 12, 0).getTime()
// 本周的开始时间,本周的结束时间
const weekStartDate = new Date(nowYear, nowMonth, nowDate - nowDay + 1)
const weekEndDate = new Date(nowYear, nowMonth, nowDate + (7 - nowDay))
// 前后三天
const tStartDate = new Date(nowYear, nowMonth, nowDate - 2)
const tEndDate = new Date(nowYear, nowMonth, nowDate + 2)
// 此处以不能跨月做示范
return time.getTime() < monthStartDate || time.getTime() > monthEndDate
}
}
}
}
}
“fool me once,shame on you. fool me twice, shame on me.”,翻译过来的意思是“愚弄我一次,是你坏;愚弄我两次,是我蠢”。