一个基于Vue3实现的简单日历组件

以下是一个基于 Vue 3 实现的简单日历组件的代码示例。这个日历组件包含了前一个月、当前月、下一个月的日期,并且可以支持选择日期、切换月份等功能。

<template>
  <div class="calendar">
    <div class="header">
      <button class="prev" @click="prevMonth">&lt;</button>
      <div class="title">{{ title }}</div>
      <button class="next" @click="nextMonth">&gt;</button>
    </div>
    <div class="weekdays">
      <div v-for="day in daysOfWeek" :key="day" class="day">{{ day }}</div>
    </div>
    <div class="days">
      <div
        v-for="day in days"
        :key="day.date"
        :class="{
          today: isToday(day),
          selected: isSelected(day),
          notCurrentMonth: isNotCurrentMonth(day),
        }"
        @click="select(day)"
      >
        {{ day.day }}
      </div>
    </div>
  </div>
</template>

<script>
  import { ref, computed } from "vue";

  export default {
    name: "FeiCalendar",
    props: {
      selectedDate: Date,
    },
    emits: ["update:selectedDate"],
    setup(props, { emit }) {
      const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
      const currentDate = ref(new Date());
      const selectedDate = ref(props.selectedDate || currentDate.value);

      const daysOfWeek = computed(() => {
        return weekdays;
      });

      const days = computed(() => {
        const year = currentDate.value.getFullYear();
        const month = currentDate.value.getMonth();
        const daysInMonth = new Date(year, month + 1, 0).getDate();
        const daysInLastMonth = new Date(year, month, 0).getDate();
        const firstDayOfMonth = new Date(year, month, 1).getDay();

        const days = [];
        let day = 1;
        let lastMonthDay = daysInLastMonth - firstDayOfMonth + 1;
        let nextMonthDay = 1;

        for (let i = 0; i < 6 * 7; i++) {
          if (i < firstDayOfMonth) {
            days.push({
              date: new Date(year, month - 1, lastMonthDay),
              day: lastMonthDay,
              isLastMonth: true,
              isNextMonth: false,
            });
            lastMonthDay++;
          } else if (i >= firstDayOfMonth + daysInMonth) {
            days.push({
              date: new Date(year, month + 1, nextMonthDay),
              day: nextMonthDay,
              isLastMonth: false,
              isNextMonth: true,
            });
            nextMonthDay++;
          } else {
            const date = new Date(year, month, day);
            days.push({ date, day, isLastMonth: false, isNextMonth: false });
            day++;
          }
        }

        return days;
      });

      const title = computed(
        () =>
          `${currentDate.value.toLocaleString("default", {
            month: "long",
          })} ${currentDate.value.getFullYear()}`
      );

      const prevMonth = () => {
        currentDate.value = new Date(
          currentDate.value.getFullYear(),
          currentDate.value.getMonth() - 1,
          1
        );
      };

      const nextMonth = () => {
        currentDate.value = new Date(
          currentDate.value.getFullYear(),
          currentDate.value.getMonth() + 1,
          1
        );
      };

      const isToday = (day) => {
        const today = new Date();
        return day.date.toDateString() === today.toDateString();
      };

      const isSelected = (day) => {
        return day.date.toDateString() === selectedDate.value.toDateString();
      };

      const isNotCurrentMonth = (day) => {
        return day.isLastMonth || day.isNextMonth;
      };

      const select = (day) => {
        selectedDate.value = day.date;
        emit("update:selectedDate", day.date);
      };

      return {
        daysOfWeek,
        days,
        title,
        prevMonth,
        nextMonth,
        isToday,
        isSelected,
        isNotCurrentMonth,
        select,
      };
    },
  };
</script>

<style>
  .calendar {
    max-width: 500px;
    margin: 0 auto;
    font-family: Arial, sans-serif;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .title {
    font-size: 18px;
    font-weight: bold;
  }

  .weekdays {
    display: flex;
    justify-content: space-around;
    margin-bottom: 10px;
  }

  .day {
    width: 30px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
  }

  .days {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-gap: 10px;
  }

  .today {
    background-color: lightblue;
  }

  .selected {
    background-color: blue;
    color: white;
  }

  .notCurrentMonth {
    color: #ccc;
  }
</style>

 使用该组件时,可以将selectedDate属性绑定到一个父组件中的数据,这个数据将会存储选中的日期。例如:

<template>
  <div>
    <!-- 用法一 -->
    <FeiCalendar
      :selectedDate="selectedDate"
      @update:selectedDate="onSelectedDateUpdated"
    />
    <!-- 用法二 -->
    <!-- <FeiCalendar v-model:selectedDate="selectedDate" /> -->
    <p>Selected date: {{ selectedDate }}</p>
  </div>
</template>

<script>
  import FeiCalendar from "./FeiCalendar.vue";

  export default {
    components: {
      FeiCalendar,
    },
    data() {
      return {
        selectedDate: new Date(),
      };
    },
    watch: {
      selectedDate(nv) {
        console.log("nv", nv);
      },
    },
    methods: {
      onSelectedDateUpdated(selectedDate) {
        this.selectedDate = selectedDate;
      },
    },
  };
</script>

 这是一个简单的示例,可以根据自己的需求对代码进行修改和扩展。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单Vue3 日历组件实现示例: ```html <template> <div> <div class="calendar-header"> <button @click="prevMonth">上个月</button> <h3>{{ monthStr }}</h3> <button @click="nextMonth">下个月</button> </div> <div class="calendar-grid"> <div v-for="(day, index) in days" :key="index" :class="{ 'calendar-cell': true, 'calendar-cell-disabled': !day }"> {{ day }} </div> </div> </div> </template> <script> import { computed, reactive } from 'vue' export default { setup() { const state = reactive({ currentMonth: new Date(), days: [] }) const prevMonth = () => { state.currentMonth.setMonth(state.currentMonth.getMonth() - 1) } const nextMonth = () => { state.currentMonth.setMonth(state.currentMonth.getMonth() + 1) } const monthStr = computed(() => { return state.currentMonth.toLocaleString('default', { month: 'long', year: 'numeric' }) }) const generateCalendar = () => { const firstDay = new Date(state.currentMonth.getFullYear(), state.currentMonth.getMonth(), 1).getDay() const lastDay = new Date(state.currentMonth.getFullYear(), state.currentMonth.getMonth() + 1, 0).getDate() const days = new Array(35).fill(null) for (let i = 1; i <= lastDay; i++) { days[firstDay + i - 1] = i } state.days = days } generateCalendar() return { state, prevMonth, nextMonth, monthStr } } } </script> <style> .calendar-grid { display: grid; grid-template-columns: repeat(7, 1fr); } .calendar-cell { border: 1px solid #ccc; padding: 10px; text-align: center; } .calendar-cell-disabled { opacity: 0.3; } </style> ``` 这个组件使用了 Vue3 的 `reactive` 和 `computed` 函数来声明响应式状态和计算属性。它还使用了 JavaScript 的 `Date` 对象来计算日历表格中的日期。在 `setup` 函数中,我们定义了一些帮助函数来生成日历,并将它们绑定到组件的方法中。最后,我们通过使用 CSS Grid 布局来组织日历表格的每个单元格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧郁的蛋~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值