vue日历表格实现
Vue 日历表格实现方法
基础日历表格结构
使用 Vue 的模板语法构建日历表格框架,通过 v-for 循环生成日期单元格。核心是计算当前月份的天数及起始星期位置。
<template>
<div class="calendar">
<div class="header">
<button @click="prevMonth">上一月</button>
<h2>{{ currentYear }}年{{ currentMonth + 1 }}月</h2>
<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="(date, index) in calendarDays"
:key="index"
:class="{ 'other-month': !date.isCurrentMonth }"
>
{{ date.day }}
</div>
</div>
</div>
</template>
计算日历数据
在 Vue 的 data 或 computed 中定义计算逻辑,生成当前月份的日期数组,并处理跨月显示。
<script>
export default {
data() {
return {
currentDate: new Date(),
weekdays: ['日', '一', '二', '三', '四', '五', '六']
};
},
computed: {
currentYear() {
return this.currentDate.getFullYear();
},
currentMonth() {
return this.currentDate.getMonth();
},
calendarDays() {
const year = this.currentYear;
const month = this.currentMonth;
const firstDay = new Date(year, month, 1).getDay();
const daysInMonth = new Date(year, month + 1, 0).getDate();
const days = [];
// 填充上个月末尾的日期
for (let i = 0; i < firstDay; i++) {
days.push({
day: new Date(year, month, -i).getDate(),
isCurrentMonth: false
});
}
days.reverse();
// 填充当前月日期
for (let i = 1; i <= daysInMonth; i++) {
days.push({
day: i,
isCurrentMonth: true
});
}
// 填充下个月开始的日期
const remainingCells = 42 - days.length; // 6行x7列
for (let i = 1; i <= remainingCells; i++) {
days.push({
day: i,
isCurrentMonth: false
});
}
return days;
}
},
methods: {
prevMonth() {
this.currentDate = new Date(this.currentYear, this.currentMonth - 1, 1);
},
nextMonth() {
this.currentDate = new Date(this.currentYear, this.currentMonth + 1, 1);
}
}
};
</script>
样式优化
通过 CSS 美化日历表格,区分当前月份与非当前月份的日期样式。
<style scoped>
.calendar {
width: 100%;
max-width: 600px;
margin: 0 auto;
font-family: Arial, sans-serif;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.weekdays, .days {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
}
.weekdays div {
text-align: center;
font-weight: bold;
padding: 10px;
}
.days div {
height: 40px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #eee;
cursor: pointer;
}
.days div.other-month {
color: #ccc;
}
</style>
高级功能扩展
为日历添加事件处理功能,例如点击日期触发事件或标记特定日期。
methods: {
handleDateClick(date) {
if (date.isCurrentMonth) {
console.log(`选中日期: ${this.currentYear}-${this.currentMonth + 1}-${date.day}`);
}
}
}
在模板中绑定点击事件:
<div
v-for="(date, index) in calendarDays"
:key="index"
:class="{ 'other-month': !date.isCurrentMonth }"
@click="handleDateClick(date)"
>
{{ date.day }}
</div>
第三方库集成
如需更复杂功能,可集成第三方日历库如 v-calendar:
npm install v-calendar
基础使用示例:
import VCalendar from 'v-calendar';
Vue.use(VCalendar);
<template>
<v-calendar :attributes="attributes" />
</template>
<script>
export default {
data() {
return {
attributes: [
{
key: 'today',
dot: 'red',
dates: new Date()
}
]
};
}
};
</script>






