vue表格实现日历
Vue 表格实现日历的方法
基础表格结构
使用 el-table 或原生 HTML 表格,通过 v-for 循环生成日历格子。月份天数通过 new Date() 计算,动态渲染表格内容。
<template>
<div>
<table class="calendar-table">
<thead>
<tr>
<th v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">{{ day }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, index) in calendarData" :key="index">
<td v-for="(date, i) in week" :key="i">{{ date || '' }}</td>
</tr>
</tbody>
</table>
</div>
</template>
动态生成日历数据
通过 JavaScript 计算当前月份的天数和起始星期,生成二维数组格式的日历数据。
<script>
export default {
data() {
return {
currentYear: new Date().getFullYear(),
currentMonth: new Date().getMonth()
}
},
computed: {
calendarData() {
const firstDay = new Date(this.currentYear, this.currentMonth, 1).getDay()
const daysInMonth = new Date(this.currentYear, this.currentMonth + 1, 0).getDate()
let date = 1
const weeks = []
for (let i = 0; i < 6; i++) {
const week = []
for (let j = 0; j < 7; j++) {
if ((i === 0 && j < firstDay) || date > daysInMonth) {
week.push(null)
} else {
week.push(date++)
}
}
weeks.push(week)
if (date > daysInMonth) break
}
return weeks
}
}
}
</script>
样式优化
添加 CSS 美化日历表格,使其更接近传统日历外观。
<style scoped>
.calendar-table {
width: 100%;
border-collapse: collapse;
}
.calendar-table th, .calendar-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
}
.calendar-table td:hover {
background-color: #f5f5f5;
}
</style>
高级功能扩展
- 日期点击事件:为
td添加@click事件处理选中日期 - 月份切换:添加按钮控制
currentMonth的增减 - 事件标记:在特定日期格子中通过
v-if显示事件图标 - 响应式布局:通过 CSS 媒体查询适配移动端
methods: {
handleDateClick(date) {
if (date) {
console.log(`选中日期: ${this.currentYear}-${this.currentMonth+1}-${date}`)
}
},
changeMonth(offset) {
this.currentMonth += offset
// 处理年份跨年
if (this.currentMonth < 0) {
this.currentMonth = 11
this.currentYear--
} else if (this.currentMonth > 11) {
this.currentMonth = 0
this.currentYear++
}
}
}
第三方库集成
对于复杂需求,可考虑集成专用日历库:
- FullCalendar:通过
@fullcalendar/vue包装器使用 - Vuetify:使用
<v-calendar>组件快速实现 - Element UI:结合
el-date-picker和自定义表格
npm install @fullcalendar/vue @fullcalendar/daygrid
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
export default {
components: {
FullCalendar
},
data() {
return {
calendarOptions: {
plugins: [dayGridPlugin],
initialView: 'dayGridMonth'
}
}
}
}






