Preventing Cross-Year Selection
The el-date-picker component in Element UI is highly customizable. A common requirement is to restrict date range selection to a single year. This can be achieved by leveraging the picker-options prop, specifically the disabledDate and onPick hooks.
The following example demonstrates how to disable dates from different years once the first date in the range is selected.
<template>
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator="to"
start-placeholder="Start date"
end-placeholder="End date"
:picker-options="yearPickerOptions"
/>
</template>
export default {
data() {
return {
dateRange: [],
firstSelectedDate: null,
yearPickerOptions: {
onPick: ({ minDate, maxDate }) => {
// Store the first selected date
if (minDate && !maxDate) {
this.firstSelectedDate = minDate;
} else {
// Clear the stored date when the range is complete
this.firstSelectedDate = null;
}
},
disabledDate: (time) => {
// If a first date has been selected, disable dates from other years
if (this.firstSelectedDate) {
return this.firstSelectedDate.getFullYear() !== new Date(time).getFullYear();
}
return false;
}
}
};
}
};
Preventing Cross-Month, Cross-Year, or Cross-Week Selection
A more flexible approach allows you to restrict the selection to a specific period, such as a single month, year, or week. The logic involves calculating the start and end bonudaries of the desired period based on the first selected date.
In this example, we'll focus on preventing cross-month selection.
<template>
<el-date-picker
v-model="restrictedRange"
type="daterange"
range-separator="to"
start-placeholder="Start date"
end-placeholder="End date"
:picker-options="rangePickerOptions"
/>
</template>
export default {
data() {
return {
restrictedRange: [],
baseDate: null,
rangePickerOptions: {
onPick: ({ minDate, maxDate }) => {
// Store the timestamp of the first selected date
if (minDate && !maxDate) {
this.baseDate = minDate.getTime();
} else {
this.baseDate = null;
}
},
disabledDate: (time) => {
if (this.baseDate) {
const selectedDate = new Date(this.baseDate);
const year = selectedDate.getFullYear();
const month = selectedDate.getMonth();
// Calculate the start and end of the current month
const startOfMonth = new Date(year, month, 1).getTime();
const endOfMonth = new Date(year, month + 1, 0).getTime();
// Disable dates outside the current month
return time < startOfMonth || time > endOfMonth;
}
return false;
}
}
};
}
};