vue表格实现日历
Vue 表格实现日历的方法
使用 Vue 结合表格实现日历功能,可以通过动态生成表格单元格的方式展示日期。以下是一种常见的实现方案:
基础日历结构
创建 Vue 组件,使用 <table> 元素构建日历框架。需要计算当前月份的天数及起始星期:
<template>
<div class="calendar">
<table>
<thead>
<tr>
<th v-for="day in weekDays" :key="day">{{ day }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, index) in weeks" :key="index">
<td v-for="(date, i) in week" :key="i">
{{ date.getDate() }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
weekDays: ['日', '一', '二', '三', '四', '五', '六'],
currentDate: new Date()
}
},
computed: {
weeks() {
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)
let days = []
// 填充上月剩余天数
for (let i = 0; i < firstDay.getDay(); i++) {
days.push(new Date(year, month, -i))
}
// 当月天数
for (let i = 1; i <= lastDay.getDate(); i++) {
days.push(new Date(year, month, i))
}
// 填充下月天数
const remaining = 7 - (days.length % 7)
for (let i = 1; i <= remaining; i++) {
days.push(new Date(year, month + 1, i))
}
// 按周分组
let weeks = []
for (let i = 0; i < days.length; i += 7) {
weeks.push(days.slice(i, i + 7))
}
return weeks
}
}
}
</script>
添加交互功能
为日历添加月份切换和日期选择功能:

<template>
<div>
<button @click="prevMonth">上个月</button>
<span>{{ currentDate.getFullYear() }}年{{ currentDate.getMonth() + 1 }}月</span>
<button @click="nextMonth">下个月</button>
<table>
<!-- ...表格结构同上... -->
<td
v-for="(date, i) in week"
:key="i"
:class="{
'current-month': date.getMonth() === currentDate.getMonth(),
'selected': selectedDate && date.toDateString() === selectedDate.toDateString()
}"
@click="selectDate(date)"
>
{{ date.getDate() }}
</td>
<!-- ... -->
</table>
</div>
</template>
<script>
export default {
data() {
return {
selectedDate: null
}
},
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
)
},
selectDate(date) {
this.selectedDate = date
}
}
}
</script>
样式优化
添加 CSS 美化日历外观:
.calendar {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: center;
border: 1px solid #ddd;
}
th {
background-color: #f5f5f5;
}
td.current-month {
background-color: white;
}
td:not(.current-month) {
color: #ccc;
}
td.selected {
background-color: #1890ff;
color: white;
}
高级功能扩展
-
事件标记:在特定日期显示标记点

<td v-for="(date, i) in week" :key="i"> <div class="date-cell"> {{ date.getDate() }} <span v-if="hasEvent(date)" class="event-dot"></span> </div> </td> -
周视图切换:添加周视图模式
data() { return { viewMode: 'month' // 或 'week' } }, computed: { weeks() { if (this.viewMode === 'week') { // 返回当周数据 } else { // 返回整月数据 } } } -
拖拽功能:实现事件拖拽到不同日期
<td @dragover.prevent @drop="handleDrop(date)" > <!-- 单元格内容 --> </td>
通过以上方法,可以构建一个功能完善的 Vue 表格日历组件,根据需求可进一步扩展功能。






