vue日历表格实现
Vue 日历表格实现方法
基础日历表格结构
使用 Vue 的模板语法构建日历表格框架,通过 v-for 循环生成日期格子。核心是计算当前月份的天数及起始星期位置。
<template>
<div class="calendar">
<div class="header">
<span v-for="day in weekDays" :key="day">{{ day }}</span>
</div>
<div class="body">
<div
v-for="date in visibleDates"
:key="date.id"
:class="{ 'other-month': !date.isCurrentMonth }"
>
{{ date.day }}
</div>
</div>
</div>
</template>
日期计算逻辑
在 Vue 的 data 或 computed 中定义日期生成方法,需处理跨月显示的日期(上个月末和下个月初的日期)。
export default {
data() {
return {
currentDate: new Date(),
weekDays: ['日', '一', '二', '三', '四', '五', '六']
}
},
computed: {
visibleDates() {
const year = this.currentDate.getFullYear();
const month = this.currentDate.getMonth();
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
// 生成当前月日期
const dates = Array.from({ length: daysInMonth }, (_, i) => ({
day: i + 1,
isCurrentMonth: true
}));
// 补全上月剩余日期
const prevMonthDays = firstDay;
for (let i = 0; i < prevMonthDays; i++) {
dates.unshift({
day: new Date(year, month, -i).getDate(),
isCurrentMonth: false
});
}
// 补全下月起始日期(确保6行显示)
const totalCells = Math.ceil(dates.length / 7) * 7;
const nextMonthDays = totalCells - dates.length;
for (let i = 1; i <= nextMonthDays; i++) {
dates.push({
day: i,
isCurrentMonth: false
});
}
return dates;
}
}
}
样式布局
使用 CSS Grid 或 Flexbox 实现日历的网格布局,注意区分当前月与其他月的样式差异。
.calendar {
width: 100%;
max-width: 600px;
}
.header {
display: grid;
grid-template-columns: repeat(7, 1fr);
text-align: center;
font-weight: bold;
}
.body {
display: grid;
grid-template-columns: repeat(7, 1fr);
grid-gap: 8px;
}
.body div {
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #eee;
}
.other-month {
color: #ccc;
}
交互功能扩展
增加月份切换和日期点击事件,通过方法修改 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
);
},
handleDateClick(date) {
if (date.isCurrentMonth) {
console.log('Selected date:', date.day);
}
}
}
使用第三方库(可选)
对于复杂需求(如拖拽事件、农历显示),可集成专用日历库:
- Vue2:
v-calendar - Vue3:
@vuepic/vue-datepicker安装后通过组件化方式快速实现:
import { VCalendar } from 'v-calendar';
export default {
components: { VCalendar }
}






