elementplus calendar 带节假日
时间: 2025-07-04 08:21:09 浏览: 19
在 Element Plus 的 `el-calendar` 组件中,虽然官方并未直接提供节假日显示的功能,但可以通过自定义日历单元格内容的方式实现这一需求。具体做法是利用 `el-calendar` 提供的插槽功能,在每个日期单元格中添加额外的信息(如节假日名称),从而实现带节假日信息的日历展示。
### 实现思路
1. **准备节假日数据**
需要提前准备一个包含节假日信息的对象或数组,其中键为日期字符串(如 `'2025-01-01'`),值为该日期对应的节假日名称(如 `'元旦'`)。
2. **使用插槽自定义日历单元格内容**
`el-calendar` 支持通过具名插槽 `default` 自定义每个日期单元格的内容。可以在此插槽中根据当前日期判断是否为节假日,并显示相应的文字。
3. **动态绑定样式以突出节假日**
可以为节假日单元格添加特定的 CSS 类,使其在视觉上区别于普通日期。
### 示例代码
```vue
<template>
<el-calendar v-model="selectedDate">
<template #default="{ date, cellType }">
<div v-if="cellType === 'date'" class="calendar-cell">
<span>{{ date.getDate() }}</span>
<span v-if="isHoliday(date)" class="holiday-label">{{ getHolidayName(date) }}</span>
</div>
</template>
</el-calendar>
</template>
<script setup>
import { ref } from 'vue'
const selectedDate = ref(new Date())
// 节假日数据示例
const holidays = {
'2025-01-01': '元旦',
'2025-02-10': '春节',
'2025-04-04': '清明节',
'2025-05-01': '劳动节',
'2025-06-01': '儿童节'
}
// 判断是否为节假日
function isHoliday(date) {
const key = formatDate(date)
return key in holidays
}
// 获取节假日名称
function getHolidayName(date) {
const key = formatDate(date)
return holidays[key] || ''
}
// 格式化日期为 YYYY-MM-DD
function formatDate(date) {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}-${month}-${day}`
}
</script>
<style scoped>
.calendar-cell {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
}
.holiday-label {
font-size: 12px;
color: red;
}
</style>
```
### 效果说明
- 上述代码中,`el-calendar` 使用了 `v-model` 绑定当前选中的日期。
- 通过 `#default` 插槽,可以访问到每个日期单元格的 `date` 和 `cellType` 参数。
- 在 `holidays` 对象中存储了部分节假日信息,通过 `isHoliday` 函数判断当前日期是否为节假日,并通过 `getHolidayName` 返回对应的节日名称。
- 最终在日历中,节假日会以红色小字显示在日期下方,形成视觉上的区分[^1]。
### 注意事项
- 如果需要处理更复杂的节假日逻辑(如农历、跨多天假期等),建议引入第三方库(如 `date-fns` 或 `moment`)进行日期计算。
- 若项目中有后端支持,也可以通过接口动态获取节假日数据,提升灵活性和可维护性。
---
阅读全文
相关推荐


















