编写一段vue代码,要求:根据日历排课,每一页显示一个月的日历
时间: 2023-05-30 12:07:07 浏览: 298
用vue设计一个日历表
<template>
<div class="calendar">
<div class="month">
<h2>{{ monthName }} {{ year }}</h2>
<table>
<thead>
<tr>
<th v-for="day in days">{{ day }}</th>
</tr>
</thead>
<tbody>
<tr v-for="week in weeks">
<td v-for="day in week">
<div class="day">{{ day.date }}</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
days: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
weeks: [],
year: null,
month: null,
monthName: null
}
},
mounted() {
this.calculateCalendarData(new Date())
},
methods: {
calculateCalendarData(date) {
this.year = date.getFullYear()
this.month = date.getMonth()
this.monthName = this.getMonthName(this.month)
const firstDayOfMonth = new Date(this.year, this.month, 1)
const lastDayOfMonth = new Date(this.year, this.month + 1, 0)
const daysInMonth = lastDayOfMonth.getDate()
const firstDayOfWeek = firstDayOfMonth.getDay()
const weeks = [[]]
let currentWeek = 0
for (let i = 0; i < firstDayOfWeek; i++) {
weeks[currentWeek].push(null)
}
for (let i = 1; i <= daysInMonth; i++) {
if (weeks[currentWeek].length === 7) {
currentWeek++
weeks.push([])
}
weeks[currentWeek].push({ date: i })
}
while (weeks[currentWeek].length < 7) {
weeks[currentWeek].push(null)
}
this.weeks = weeks
},
getMonthName(month) {
const monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
return monthNames[month]
}
}
}
</script>
<style>
.calendar {
margin: 20px auto;
max-width: 600px;
text-align: center;
}
.month {
margin-bottom: 20px;
}
table {
border-collapse: collapse;
margin: 0 auto;
}
thead th {
padding: 10px;
text-transform: uppercase;
}
tbody td {
padding: 10px;
border: 1px solid #ccc;
}
.day {
height: 50px;
display: flex;
justify-content: center;
align-items: center;
}
.day:hover {
background-color: #f2f2f2;
}
</style>
阅读全文