这段代码是一个使用 Vue 3 框架编写的简单日历组件。下面是代码的详细解析:
模板部分(Template):
- 定义了一个名为 "calendar" 的 div,它包含了一个头部分(header)和三个主要部分:一周的日期(days-of-week)、所有日期(dates)和一个按钮组。
- 在 "header" 部分,显示了当前的年和月,以及两个按钮,一个用于显示上个月,另一个用于显示下个月。
- "days-of-week" 部分显示了一周的七天。
- "dates" 部分显示了该月的所有日期。使用
v-for
指令来循环遍历dates
数组,并显示每个日期的天数。同时,使用:class
绑定来为当前月份以外的日期添加一个特定的 CSS 类("not-current-month")。
脚本部分(Script):
- 使用
import { ref, computed } from 'vue'
导入了 Vue 的响应式引用(ref)和计算属性(computed)。 - 定义了四个响应式引用:
year
、month
、daysOfWeek
和dates
。 year
和month
引用了当前年份和月份。daysOfWeek
是一个包含一周七天的数组。dates
是一个计算属性,它首先获取当前月份的第一天是星期几,然后确定这个月有多少天,并创建一个包含所有这些日期的数组。然后,它使用Array.prototype.fill()
方法填充数组中的前几项,这些项对应于一周的前几天(例如,如果一周的第一天是星期日,那么数组的前一项将是空对象)。previousMonth
和nextMonth
函数分别用于显示上个月和下个月的日历。这些函数通过修改year
和month
的值来实现。
- 使用
样式部分(Style):
- 在这里可以添加你的样式代码,以定制日历的外观。由于此代码示例中没有提供样式部分,因此默认情况下它将使用 Vue 的内置样式或任何全局样式表中的样式。
总的来说,这是一个功能齐全的、可响应的、用户可操作的日历组件
代码部分
<template>
<div class="calendar">
<div class="header">
<span>{
{ year }} 年 {
{ month + 1 }} 月</span>
<button @click="previousMonth">上个月</button>
<button @click="nextMonth">下个月</button>
</div>
<div class="days-of-week">
<span v-for="day in daysOfWeek" :key="day">{
{ day }}</span>
</div>
<div class="dates">
<span
v-for="(date, index) in dates"
:key="index"
:class="{ 'not-current-month': date.month !== month }"
>
{
{ date.day }}
</span>
</div>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const year = ref(new Date().getFullYear());
const month = ref(new Date().getMonth());
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const dates = computed(() => {
const firstDayOfMonth = new Date(year.value, month.value, 1).getDay();
const totalDaysInMonth = new Date(year.value, month.value + 1, 0).getDate();
const datesArray = [];
for (let i = 1; i <= totalDaysInMonth; i++) {
datesArray.push({ day: i, month: month.value });
}
return [
...Array(firstDayOfMonth).fill({ day: '', month: '' }),
...datesArray,
];
});
function previousMonth() {
if (month.value === 0) {
year.value--;
month.value = 11;
} else {
month.value--;
}
}
function nextMonth() {
if (month.value === 11) {
year.value++;
month.value = 0;
} else {
month.value++;
}
}
</script>
<style scoped>
/* Add your styles here */
</style>