Customizing the Element UI Calendar Component
To customize the Element UI calendar component for displaying specific data, we can leverage its slot system. The following example demonstrates how to show custom information for selected dates while hiding others.
The calendar component is structured as follows:
<el-calendar v-model="selectedDate">
<template #dateCell="{ cellDate, cellData }">
<template v-if="visibleDates.includes(cellData.day)">
<div class="custom-date-title">
{{ cellData.day.split('-').slice(2).join('-') }}
<i class="el-icon-document"></i>
</div>
<template v-if="dateInfoMap[cellData.day]">
<div class="info-panel">
<div class="info-item">
<span>People:</span>
<span>{{ dateInfoMap[cellData.day].numPeople }}</span>
</div>
<div class="info-item">
<span>Hours:</span>
<span>{{ dateInfoMap[cellData.day].workingHours }}</span>
</div>
</div>
</template>
</template>
</template>
</el-calendar>
The visibleDates computed property generates an array of dates for the currently viewed month. This ensures that only dates from the target month are processed and displayed.
visibleDates() {
const today = this.currentDate;
let monthOffset = 0;
switch (this.viewMode) {
case 'previous':
monthOffset = -1;
break;
case 'current':
monthOffset = 0;
break;
case 'next':
monthOffset = 1;
break;
default:
monthOffset = 0;
}
const year = today.getFullYear();
let month = today.getMonth() + 1 + monthOffset;
const daysInMonth = new Date(year, month, 0).getDate();
const dateList = [];
for (let i = 1; i <= daysInMonth; i++) {
dateList.push(dayjs(`${year}-${month}-${i}`).format('YYYY-MM-DD'));
}
return dateList;
}
To efficiently access data to a specific date, we transform the raw data array into a map where the date string is the key.
transformRawData() {
this.dateInfoMap = this.rawData.reduce((map, item) => {
map[item.date] = { ...item };
return map;
}, {});
}
To prevent users from interacting with or seeing dates from adjacent months, apply the following CSS:
/* Disable and hide dates from previous month */
:deep(.el-calendar-table td.prev) {
pointer-events: none;
display: none;
}
/* Disable and hide dates from next month */
:deep(.el-calendar-table td.next) {
pointer-events: none;
display: none;
}