vue VUE实现日历组件功能
Vue 日历组件实现方法
基础日历结构
使用Vue的模板语法构建日历的HTML结构,通常包含头部(年月显示、切换按钮)和日历表格(星期标题和日期格子)。
<template>
<div class="calendar">
<div class="header">
<button @click="prevMonth">上个月</button>
<span>{{ currentYear }}年{{ currentMonth }}月</span>
<button @click="nextMonth">下个月</button>
</div>
<div class="weekdays">
<div v-for="day in weekdays" :key="day">{{ day }}</div>
</div>
<div class="days">
<div
v-for="(day, index) in days"
:key="index"
:class="{ 'other-month': !day.isCurrentMonth }"
@click="selectDay(day)"
>
{{ day.date }}
</div>
</div>
</div>
</template>
日期数据处理
计算当前月份的天数和前后月份的补全日期,确保日历表格完整显示6行。
data() {
return {
currentDate: new Date(),
weekdays: ['日', '一', '二', '三', '四', '五', '六']
}
},
computed: {
days() {
const year = this.currentDate.getFullYear()
const month = this.currentDate.getMonth()
const firstDay = new Date(year, month, 1)
const lastDay = new Date(year, month + 1, 0)
const days = []
// 上个月补全天数
const prevMonthDays = firstDay.getDay()
for (let i = prevMonthDays - 1; i >= 0; i--) {
days.push({
date: new Date(year, month, -i).getDate(),
isCurrentMonth: false
})
}
// 当月天数
for (let i = 1; i <= lastDay.getDate(); i++) {
days.push({
date: i,
isCurrentMonth: true,
fullDate: new Date(year, month, i)
})
}
// 下个月补全天数
const nextMonthDays = 42 - days.length
for (let i = 1; i <= nextMonthDays; i++) {
days.push({
date: i,
isCurrentMonth: false
})
}
return days
},
currentYear() {
return this.currentDate.getFullYear()
},
currentMonth() {
return this.currentDate.getMonth() + 1
}
}
月份切换功能
实现上个月和下个月的切换逻辑,更新currentDate数据。
methods: {
prevMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() - 1,
1
)
},
nextMonth() {
this.currentDate = new Date(
this.currentDate.getFullYear(),
this.currentDate.getMonth() + 1,
1
)
},
selectDay(day) {
if (day.isCurrentMonth) {
console.log('选择的日期:', day.fullDate)
}
}
}
样式设计
添加基础CSS样式,使日历显示美观。
.calendar {
width: 350px;
font-family: Arial;
}
.header {
display: flex;
justify-content: space-between;
padding: 10px;
background: #f0f0f0;
}
.weekdays {
display: grid;
grid-template-columns: repeat(7, 1fr);
background: #e0e0e0;
}
.days {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 1px;
background: #ccc;
}
.days > div {
padding: 10px;
background: white;
height: 40px;
}
.other-month {
color: #aaa;
}
进阶功能扩展
可根据需求添加以下功能:
- 日期范围选择
- 标记特殊日期
- 多语言支持
- 事件显示
- 移动端适配
// 示例:标记今天
computed: {
days() {
// ...原有代码
const today = new Date()
days.forEach(day => {
if (day.fullDate &&
day.fullDate.getDate() === today.getDate() &&
day.fullDate.getMonth() === today.getMonth() &&
day.fullDate.getFullYear() === today.getFullYear()) {
day.isToday = true
}
})
return days
}
}
/* 添加今天样式 */
.today {
background: #ffeb3b !important;
font-weight: bold;
}






