信息发布→ 登录 注册 退出

从零写vue日历组件

发布时间:2026-01-11

点击量:
目录
  • 1. 前言
  • 2. vue日历制作
    • 2.1 制作月份选择器
    • 2.2 制作日历
      • 2.2.1 获取当前月所要显示的日期
      • 2.2.2 给不同的日期添加不同的样式
    • 2.3 将月份选择器和日历组件组合使用
      • 2.4 编辑功能

      1. 前言

      最近做项目遇到一个需求,需要制作一个定制化的日历组件(项目使用的UI框架不能满足需求,算了,我直说了吧,ant design vue的日历组件是真的丑,所以就自己写了一个),如下图所示,需求大致如下:
      (2)日历可以按照月份进行上下月的切换。
      (2)按照月份展示周一到周日的排班信息。
      (3)排班信息分为早班和晚班。
      (4)按照日期对排班进行颜色区分:当前月份排班信息正常颜色,今天显示深色,其他月份显示浅色。
      (5)点击编辑按钮,日历进入编辑模式。简单点说就是,今天和今天之后的排班右侧都显示一个选择按钮,点击后可弹框编辑当日的排班人员。

      如果只需要日历组件部分,可以直接看2.2部分,只需要传递当前时间(一个包含当前年份和月份的对象),即可展示完整的当前月日历。

      2. vue日历制作

      因为项目使用的是ant desgin vue框架,所以会有a-row、a-col、a-card等标签,如果是使用elementUI,将标签替换成对应的el-row、el-col、el-card等标签即可。

      2.1 制作月份选择器

      效果示意图:

      按照需求,我们首先需要制作一个月份选择器,用于提供月份的切换,默认显示当前月。点击左侧箭头向前一个月,点击右侧箭头向后一个月,并且每次点击都会向外抛出changeMonth函数,携带对象time,包含当前月份选择器的年份和月份。

      <template>
        <!-- 月份选择器,支持左右箭头修改月份 -->
        <div class="month-con">
          <a-icon type="left" @click="reduceMonth()" />
          <span class="month"
            >{{ time.year }}年{{
              time.month + 1 > 9 ? time.month + 1 : '0' + (time.month + 1)
            }}月</span
          >
          <a-icon type="right" @click="addMonth()" />
        </div>
      </template>
      
      <script>
      export default {
        data() {
          return {
            time: {
              year: new Date().getFullYear(),
              month: new Date().getMonth()
            }
          }
        },
        created() {},
        methods: {
          reduceMonth() {
            if (this.time.month > 0) {
              this.time.month = this.time.month - 1
            } else {
              this.time.month = 11
              this.time.year = this.time.year - 1
            }
            this.$emit('changeMonth', this.time)
          },
          addMonth() {
            if (this.time.month < 11) {
              this.time.month = this.time.month + 1
            } else {
              this.time.month = 0
              this.time.year = this.time.year + 1
            }
            this.$emit('changeMonth', this.time)
          }
        }
      }
      </script>
      <style lang="less" scoped>
      .month-con {
        font-weight: 700;
        font-size: 18px;
        .month {
          margin: 0 10px;
        }
      }
      </style>
      
      

      2.2 制作日历

      2.2.1 获取当前月所要显示的日期

      在制作日历之前,我们可以先观察下电脑自带的日历。经过观察,我们可以发现以下几个规律:
      (1)虽然每个月的日总数不同,但是都统一显示6行,一共42天。
      (2)当前月的第一天在第一行,并且当1号不在周一时,会使用上个月的日期补全周一到1号的时间。
      (3)第五行和第六行不属于当前月部分,会使用下个月的日期补全。

      因此参照以上规律,获取当前月所需要展示的日期时,可以按照以下几个步骤:
      (1)获取当前月第一天所在的日期和星期几
      (2)当前月第一天星期几减1就是之前要补足的天数,将当前月第一天减去这个天数,就是日历所要展示的起始日期。比如上面日历的起始日期就是1月31日。
      (3)循环42次,从起始日期开始,每次时间加上一天,将这42天的日期存到一个数组里,就是日历所要展示的当前月所有日期。
      (4)因为每次切换月份都会重新刷新一次日历,因此可以直接将日历数组写成computed属性。

      computed: {
          // 获取当前月份显示日历,共42天
          visibleCalendar: function() {
            const calendarArr = []
            // 获取当前月份第一天
            const currentFirstDay = new Date(this.time.year, this.time.month, 1)
            // 获取第一天是周几
            const weekDay = currentFirstDay.getDay()
            // 用当前月份第一天减去周几前面几天,就是看见的日历的第一天
            const startDay = currentFirstDay - (weekDay - 1) * 24 * 3600 * 1000
            // 我们统一用42天来显示当前显示日历
            for (let i = 0; i < 42; i++) {
              const date = new Date(startDay + i * 24 * 3600 * 1000)
              calendarArr.push({
                date: new Date(startDay + i * 24 * 3600 * 1000),
                year: date.getFullYear(),
                month: date.getMonth(),
                day: date.getDate()
              })
            }
            return calendarArr
          }
        }
      

      2.2.2 给不同的日期添加不同的样式

      效果示意图:

      按照需求,我们需要给不同的日期添加不同的样式:
      (1)当前月份排班信息正常颜色
      (2)今天显示深色
      (3)其他月份显示浅色
      因此我们获取当前月日历数组的时候,就可以把每一天和今天的日期进行比较,从而添加不同的属性,用于获取添加不同的样式:
      (1)如果是当前月,则thisMonth属性为thisMonth,否则为空;
      (2)如果是当天,则isToday属性为isToday,否则为空;
      (3)如果是当前月,则afterToday属性为afterToday,否则为空;

      computed: {
          // 获取当前月份显示日历,共42天
          visibleCalendar: function() {
            // 获取今天的年月日
            const today = new Date()
            today.setHours(0)
            today.setMinutes(0)
            today.setSeconds(0)
            today.setMilliseconds(0)
      
            const calendarArr = []
            // 获取当前月份第一天
            const currentFirstDay = new Date(this.time.year, this.time.month, 1)
            // 获取第一天是周几
            const weekDay = currentFirstDay.getDay()
            // 用当前月份第一天减去周几前面几天,就是看见的日历的第一天
            const startDay = currentFirstDay - (weekDay - 1) * 24 * 3600 * 1000
            // 我们统一用42天来显示当前显示日历
            for (let i = 0; i < 42; i++) {
              const date = new Date(startDay + i * 24 * 3600 * 1000)
              calendarArr.push({
                date: new Date(startDay + i * 24 * 3600 * 1000),
                year: date.getFullYear(),
                month: date.getMonth(),
                day: date.getDate(),
                // 是否在当月
                thisMonth:
                  date.getFullYear() === today.getFullYear() &&
                  date.getMonth() === today.getMonth()
                    ? 'thisMonth'
                    : '',
                // 是否是今天
                isToday:
                  date.getFullYear() === today.getFullYear() &&
                  date.getMonth() === today.getMonth() &&
                  date.getDate() === today.getDate()
                    ? 'isToday'
                    : '',
                // 是否在今天之后
                afterToday: date.getTime() >= today.getTime() ? 'afterToday' : ''
              })
            }
            return calendarArr
          }
        }
      

      日历组件vue代码如下,在进行测试时,可以先将time的默认值设置为当前月:

      <template>
        <div>
          <a-row>
            <!-- 左侧,提示早班、晚班或者上午、下午 -->
            <a-col :span="2">
              <div class="date-con tip-con">
                <a-col
                  v-for="item in 6"
                  :key="item"
                  class="date thisMonth tip"
                  :span="1"
                >
                  <div class="morning">早班</div>
                  <div class="evening">晚班</div>
                </a-col>
              </div>
            </a-col>
            <!-- 右侧,周一到周五具体内容 -->
            <a-col :span="22">
              <!-- 第一行表头,周一到周日 -->
              <div class="top-con">
                <div class="top" v-for="item in top" :key="item">星期{{ item }}</div>
              </div>
              <!-- 日历号 -->
              <div class="date-con">
                <div
                  class="date"
                  :class="[item.thisMonth, item.isToday, item.afterToday]"
                  v-for="(item, index) in visibleCalendar"
                  :key="index"
                >
                  <div>{{ item.day }}</div>
                  <div class="morning">张三,李四</div>
                  <div class="evening">王五,赵六</div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>
      </template>
      
      <script>
      // import utils from './utils.js'
      export default {
        props: {
          time: {
            type: Object,
            default: () => {
              return {}
            }
          }
        },
        data() {
          return {
            top: ['一', '二', '三', '四', '五', '六', '日']
          }
        },
        created() {
          console.log('123', this.time)
        },
        methods: {
          // 获取
        },
        computed: {
          // 获取当前月份显示日历,共42天
          visibleCalendar: function() {
            // 获取今天的年月日
            const today = new Date()
            today.setHours(0)
            today.setMinutes(0)
            today.setSeconds(0)
            today.setMilliseconds(0)
      
            const calendarArr = []
            // 获取当前月份第一天
            const currentFirstDay = new Date(this.time.year, this.time.month, 1)
            // 获取第一天是周几
            const weekDay = currentFirstDay.getDay()
            // 用当前月份第一天减去周几前面几天,就是看见的日历的第一天
            const startDay = currentFirstDay - (weekDay - 1) * 24 * 3600 * 1000
            // 我们统一用42天来显示当前显示日历
            for (let i = 0; i < 42; i++) {
              const date = new Date(startDay + i * 24 * 3600 * 1000)
              calendarArr.push({
                date: new Date(startDay + i * 24 * 3600 * 1000),
                year: date.getFullYear(),
                month: date.getMonth(),
                day: date.getDate(),
                // 是否在当月
                thisMonth:
                  date.getFullYear() === today.getFullYear() &&
                  date.getMonth() === today.getMonth()
                    ? 'thisMonth'
                    : '',
                // 是否是今天
                isToday:
                  date.getFullYear() === today.getFullYear() &&
                  date.getMonth() === today.getMonth() &&
                  date.getDate() === today.getDate()
                    ? 'isToday'
                    : '',
                // 是否在今天之后
                afterToday: date.getTime() >= today.getTime() ? 'afterToday' : ''
              })
            }
            return calendarArr
          }
        }
      }
      </script>
      <style lang="less" scoped>
      .top-con {
        display: flex;
        align-items: center;
        .top {
          width: 14.285%;
          background-color: rgb(242, 242, 242);
          padding: 10px 0;
          margin: 5px;
          text-align: center;
        }
      }
      .date-con {
        display: flex;
        flex-wrap: wrap;
        .date {
          width: 14.285%;
          text-align: center;
          padding: 5px;
          .morning {
            padding: 10px 0;
            background-color: rgba(220, 245, 253, 0.3);
          }
          .evening {
            padding: 10px 0;
            background-color: rgba(220, 244, 209, 0.3);
          }
        }
        .thisMonth {
          .morning {
            background-color: rgb(220, 245, 253);
          }
          .evening {
            background-color: rgb(220, 244, 209);
          }
        }
        .isToday {
          font-weight: 700;
          .morning {
            background-color: rgb(169, 225, 243);
          }
          .evening {
            background-color: rgb(193, 233, 175);
          }
        }
      }
      .tip-con {
        margin-top: 51px;
        .tip {
          margin-top: 21px;
          width: 100%;
        }
      }
      </style>
      
      

      2.3 将月份选择器和日历组件组合使用

      效果示意图:

      组合代码如下:

      <template>
        <div>
          <a-card>
            <!-- 操作栏 -->
            <a-row type="flex" justify="space-around">
              <a-col :span="12">
                <!-- 月份选择器 -->
                <monthpicker @changeMonth="changeMonth"></monthpicker>
              </a-col>
              <a-col :span="12"></a-col>
            </a-row>
            <!-- 日历栏 -->
            <a-row class="calendar-con">
              <calendar :time="time"></calendar>
            </a-row>
          </a-card>
        </div>
      </template>
      
      <script>
      // 月份选择器
      import Monthpicker from './components/Monthpicker.vue'
      // 日历组件
      import Calendar from './components/Calendar.vue'
      export default {
        components: {
          monthpicker: Monthpicker,
          calendar: Calendar
        },
        data() {
          return {
            time: {
              year: new Date().getFullYear(),
              month: new Date().getMonth()
            }
          }
        },
        created() {},
        methods: {
          // 修改月份
          changeMonth(time) {
            console.log('time', time)
            this.time = time
          }
        }
      }
      </script>
      <style lang="less" scoped>
      .month-con {
        font-weight: 700;
        font-size: 18px;
        .month {
          margin: 0 10px;
        }
      }
      .calendar-con {
        margin-top: 20px;
      }
      </style>
      
      

      通过changeMonth事件,将月份选择器的月份传递给日历组件,这样就完成了一个简单的能够修改月份的日历组件了。

      2.4 编辑功能

      效果示意图:

      根据需求,我们还需要对日历的内容具有编辑能力。具体需求为在日历上方添加一个编辑按钮,点击后将日历切换为编辑模式,其实就是每个格子的值班信息后显示一个选择按钮,点击后弹出弹框或者跳转至编辑页,用于修改当前格子的值班信息。完成修改后点击保存,关闭弹框或者返回日历页,重新查询当前日历值班信息。

      当然:以上只是编辑功能的其中一种实现思路,如果格子内只是文本信息,不涉及任何复杂的绑定,亦可以通过点击编辑按钮将每个格子转换成input输入框,右侧加上一个保存按钮(也可以在日历上方加上一个总的保存按钮),编辑完毕后,点击保存,再恢复至文本形式即可。

      注意:通常只有今天和今天之后的值班信息可以编辑,因此之前的日历数组中的每个日期对象我们都保存了一个afterToday属性,可以用于判断是否渲染选择按钮。 因为编辑功能过于简单,就不写代码演示了。

      在线客服
      服务热线

      服务热线

      4008888355

      微信咨询
      二维码
      返回顶部
      ×二维码

      截屏,微信识别二维码

      打开微信

      微信号已复制,请打开微信添加咨询详情!