使用 Vue 3 框架编写的简单日历组件

这段代码是一个使用 Vue 3 框架编写的简单日历组件。下面是代码的详细解析:

  1. 模板部分(Template)

    • 定义了一个名为 "calendar" 的 div,它包含了一个头部分(header)和三个主要部分:一周的日期(days-of-week)、所有日期(dates)和一个按钮组。
    • 在 "header" 部分,显示了当前的年和月,以及两个按钮,一个用于显示上个月,另一个用于显示下个月。
    • "days-of-week" 部分显示了一周的七天。
    • "dates" 部分显示了该月的所有日期。使用 v-for 指令来循环遍历 dates 数组,并显示每个日期的天数。同时,使用 :class 绑定来为当前月份以外的日期添加一个特定的 CSS 类("not-current-month")。
  2. 脚本部分(Script)

    • 使用 import { ref, computed } from 'vue' 导入了 Vue 的响应式引用(ref)和计算属性(computed)。
    • 定义了四个响应式引用:yearmonthdaysOfWeek 和 dates
    • year 和 month 引用了当前年份和月份。
    • daysOfWeek 是一个包含一周七天的数组。
    • dates 是一个计算属性,它首先获取当前月份的第一天是星期几,然后确定这个月有多少天,并创建一个包含所有这些日期的数组。然后,它使用 Array.prototype.fill() 方法填充数组中的前几项,这些项对应于一周的前几天(例如,如果一周的第一天是星期日,那么数组的前一项将是空对象)。
    • previousMonth 和 nextMonth 函数分别用于显示上个月和下个月的日历。这些函数通过修改 year 和 month 的值来实现。
  3. 样式部分(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>

  • 15
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值