<template>
<div class="calendar">
<div class="calendar-header">
<button @click="prevMonth"><</button>
<span>{{ currentMonth }} {{ currentYear }}</span>
<button @click="nextMonth">></button>
</div>
<div class="calendar-body">
<div class="day-names">
<span v-for="day in daysOfWeek" :key="day">{{ day }}</span>
</div>
<div class="days">
<span v-for="(day, index) in daysInMonth" :key="index" :class="{ 'current-day': isCurrentDay(day) }">
{{ day }}
</span>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const currentDate = ref(new Date());
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const daysInMonth = ref<number[]>([]);
const currentMonth = ref(currentDate.value.getMonth() + 1);
const currentYear = ref(currentDate.value.getFullYear());
const isCurrentDay = (day: number) => {
return (
currentDate.value.getDate() === day &&
currentDate.value.getMonth() === currentMonth.value - 1
);
};
const prevMonth = () => {
if (currentMonth.value === 1) {
currentYear.value--;
currentMonth.value = 12;
} else {
currentMonth.value--;
}
buildMonth();
};
const nextMonth = () => {
if (currentMonth.value === 12) {
currentYear.value++;
currentMonth.value = 1;
} else {
currentMonth.value++;
}
buildMonth();
};
const buildMonth = () => {
daysInMonth.value = [];
const date = new Date(currentYear.value, currentMonth.value - 1, 1);
let day = date.getDay();
let dateCounter = 1;
while (day !== 0) {
daysInMonth.value.push(dateCounter - day);
day--;
}
while (date.getMonth() === currentMonth.value - 1) {
daysInMonth.value.push(dateCounter);
dateCounter++;
date.setDate(date.getDate() + 1);
day = date.getDay();
评论已关闭