基于Vue3实现日历组件的示例代码

 更新时间:2023年04月23日 10:11:17   作者:飞仔FeiZai  
日历在很多地方都可以使用的到,这篇文章主要介绍了如何利用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>

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

到此这篇关于基于Vue3实现日历组件的示例代码的文章就介绍到这了,更多相关Vue3日历组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Nuxt.js结合Serverless构建无服务器应用

    Nuxt.js结合Serverless构建无服务器应用

    Nuxt.js是一个基于Vue.js的框架,结合Serverless架构,Nuxt.js可以让你构建高度可扩展、成本效益高的无服务器应用,具有一定的参考价值,感兴趣的可以了解一下
    2024-08-08
  • vue.js使用v-if实现显示与隐藏功能示例

    vue.js使用v-if实现显示与隐藏功能示例

    这篇文章主要介绍了vue.js使用v-if实现显示与隐藏功能,结合简单实例形式分析了使用v-if进行判断实现元素的显示与隐藏功能,需要的朋友可以参考下
    2018-07-07
  • vue实现计步器功能

    vue实现计步器功能

    这篇文章主要为大家详细介绍了vue实现计步器功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-11-11
  • Vue子组件监听父组件值的变化

    Vue子组件监听父组件值的变化

    这篇文章主要介绍了Vue子组件监听父组件值的变化方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-04-04
  • Vue自定义render统一项目组弹框功能

    Vue自定义render统一项目组弹框功能

    这篇文章主要介绍了Vue自定义render统一项目组弹框功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06
  • Vue3中ref与reactive的详解与扩展

    Vue3中ref与reactive的详解与扩展

    在vue3中对响应式数据的声明官方给出了ref()和reactive()这两种方式,下面这篇文章主要给大家介绍了关于Vue3中ref与reactive的相关资料,需要的朋友可以参考下
    2021-06-06
  • vue使用once修饰符,使事件只能触发一次问题

    vue使用once修饰符,使事件只能触发一次问题

    这篇文章主要介绍了vue使用once修饰符,使事件只能触发一次问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • vue组件Prop传递数据的实现示例

    vue组件Prop传递数据的实现示例

    本篇文章主要介绍了vue组件Prop传递数据的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • Vue组件中常见的props默认值陷阱问题

    Vue组件中常见的props默认值陷阱问题

    这篇文章主要介绍了避免Vue组件中常见的props默认值陷阱,本文通过问题展示及解决方案给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-09-09
  • Vite使用报错解决方法合集

    Vite使用报错解决方法合集

    这篇文章主要给大家介绍了关于Vite使用报错解决方法的相关资料,这篇文中通过图文以及代码将遇到的一些报错介绍的非常详细,对大家学习或者使用vite具有一定的借鉴价值,需要的朋友可以参考下
    2023-08-08

最新评论