教你从零写vue日历组件

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)
      // 获取第一天是周几,注意周日的时候getDay()返回的是0,要做特殊处理
      const weekDay =
        currentFirstDay.getDay() === 0 ? 7 : 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)
      // 获取第一天是周几,注意周日的时候getDay()返回的是0,要做特殊处理
      const weekDay =
        currentFirstDay.getDay() === 0 ? 7 : 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)
      // 获取第一天是周几,注意周日的时候getDay()返回的是0,要做特殊处理
      const weekDay =
        currentFirstDay.getDay() === 0 ? 7 : 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属性,可以用于判断是否渲染选择按钮。 因为编辑功能过于简单,就不写代码演示了。

2.5 带有节假日组件版本

主要在visibleCalendar中添加了holiday,用于和新加的props.holidays中的节假日属性进行匹配。因为篇幅和时间考虑,没有将农历的节日放进来,同学们也可以将自己认为重要的日子进行定义。
Calendar.vue:

<template>
  <div :style="`width:${width || '100%'}`" class="calendar-con">
    <!-- 左侧,提示早班、晚班或者上午、下午 -->
    <div class="calendar-left-con">
      <div class="date-con tip-con">
        <div v-for="item in 6" :key="item" class="date thisMonth tip" :span="1">
          <div class="morning">{
    
    {
    
     leftItems[0] }}</div>
          <div class="evening">{
    
    {
    
     leftItems[1] }}</div>
        </div>
      </div>
    </div>
    <!-- 右侧,周一到周五具体内容 -->
    <div class="calendar-right-con">
      <!-- 第一行表头,周一到周日 -->
      <div class="top-con">
        <div class="top" v-for="item in topItems" :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 class="number">
            <span>{
    
    {
    
     item.day }}</span>
            <div class="holiday">{
    
    {
    
     item.holiday }}</div>
          </div>
          <div class="morning">张三</div>
          <div class="evening">王五</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import utils from './utils.js'
export default {
    
    
  props: {
    
    
    // 根据传入的年份和月份,日历自动生成
    time: {
    
    
      type: Object,
      default: () => {
    
    
        return {
    
    
          year: '2022',
          month: '6'
        }
      }
    },
    // 顶部标题
    topItems: {
    
    
      type: Array,
      default: () => {
    
    
        return [
          '星期一',
          '星期二',
          '星期三',
          '星期四',
          '星期五',
          '星期六',
          '星期日'
        ]
      }
    },
    // 左侧标题
    leftItems: {
    
    
      type: Array,
      default: () => {
    
    
        return ['早班', '晚班']
      }
    },
    // 日期格式
    dataFormat: {
    
    
      type: String,
      default: ''
    },
    // 日历宽度
    width: {
    
    
      type: String,
      default: ''
    },
    // 日历高度
    height: {
    
    
      type: String,
      default: ''
    },
    // 法定节假日
    holidays: {
    
    
      type: Object,
      default: () => {
    
    
        return {
    
    
          // 一月
          '01-01': '元旦',
          '01-26': '国际海关日',
          // 二月
          '02-02': '世界湿地日',
          '02-07': '国际声援南非日',
          '02-10': '国际气象节',
          '02-14': '情人节',
          '02-15': '中国12亿人口日',
          '02-21': '国际母语日',
          '02-24': '第三世界青年日',
          '02-28': '世界居住条件调查日',
          // 三月
          '03-03': '全国爱耳日',
          '03-05': '中国青年志愿者服务日',
          '03-08': '国际劳动妇女节',
          '03-12': '中国植树节',
          '03-15': '国际消费者权益日',
          '03-21': '世界森林日',
          // 四月
          '04-01': '愚人节',
          '04-07': '世界卫生日',
          '04-22': '世界地球日',
          '04-26': '世界知识产权日',
          // 五月
          '05-01': '国际劳动节',
          '05-04': '青年节',
          '05-31': '世界无烟日',
          // 六月
          '06-01': '国际儿童节',
          '06-05': '世界环境日',
          '06-11': '中国人口日',
          '06-20': '世界难民日',
          '06-23': '世界奥林匹克日',
          '06-26': '国际反毒品日',
          '06-30': '世界青年联欢节',
          '07-01': '建党节/香港回归纪念日',
          '07-07': '中国人民抗日战争纪念日',
          '07-11': '世界人口日',
          // 八月
          '08-01': '建军节',
          '08-06': '国际电影节',
          '08-08': '中国男子节(爸爸节)',
          '08-26': '全国律师咨询日',
          // 九月
          '09-03': '中国抗日战争纪念日',
          '09-08': '世界扫盲日',
          '09-10': '中国教师节',
          '09-18': '九一八事变纪念日(中国国耻日)',
          // 十月
          '10-01': '国庆节',
          '10-04': '世界动物日',
          '10-10': '辛亥革命纪念日',
          '10-24': '联合国日',
          // 十一月
          '11-08': '中国记者日',
          '11-09': '消防节',
          '11-10': '世界青年节',
          '11-17': '国际大学生节',
          '11-21': '世界问候日',
          // 十二月
          '12-01': '世界艾滋病日',
          '12-03': '世界残疾人日',
          '12-12': '西安事变纪念日',
          '12-13': '南京大屠杀纪念日',
          '12-20': '澳门回归纪念日',
          '12-21': '国际篮球日',
          '12-24': '平安夜',
          '12-25': '圣诞节'
        }
      }
    }
  },
  data() {
    
    
    return {
    
    }
  },
  created() {
    
    
    console.log('123', this.time)
  },
  filters: {
    
    
    // dateFormat: function () {}
  },
  methods: {
    
    
    // 根据格式,获取日期
    formatDate(dateObj = {
    
     month: '', date: '' }, format = 'mm-dd') {
    
    
      if (format === 'mm-dd') {
    
    
        const month = dateObj.month > 9 ? dateObj.month : '0' + dateObj.month
        const date = dateObj.date > 9 ? dateObj.date : '0' + dateObj.date
        return month + '-' + date
      }
    }
  },
  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)
      // 获取第一天是周几,注意周日的时候getDay()返回的是0,要做特殊处理
      const weekDay =
        currentFirstDay.getDay() === 0 ? 7 : 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() + 1,
          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' : '',
          holiday:
            this.holidays[
              this.formatDate({
    
    
                month: date.getMonth() + 1,
                date: date.getDate()
              })
            ]
        })
      }
      return calendarArr
    }
  }
}
</script>
<style lang="less" scoped>
.calendar-con {
    
    
  display: flex;
  .calendar-left-con {
    
    
    width: 10%;
  }
  .calendar-right-con {
    
    
    width: 90%;
  }
}
.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 {
    
    
    text-align: center;
    width: calc(14.285% - 10px);
    padding: 0 5px;
    .number {
    
    
      // padding-top: 3px;
      padding: 10px 0;
      position: relative;
    }
    .holiday {
    
    
      position: absolute;
      width: 100%;
      top: 7px;
      left: 0;
      opacity: 0.2;
      text-align: center;
    }
    .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;
    margin-top: 38px;
    width: 100%;
  }
}
</style>

使用:

<template>
  <div id="app">
    <calendar
      :time="time"
      :topItems="topItems"
      :leftItems="leftItems"
    ></calendar>
  </div>
</template>

<script>
import calendar from './components/Calendar.vue'
export default {
    
    
  name: 'App',
  components: {
    
    
    calendar
  },
  data() {
    
    
    return {
    
    
      time: {
    
    
        year: '2022',
        // 日历传入6,其实是7月
        month: '6'
      },
      topItems: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      leftItems: ['上午', '下午']
    }
  }
}
</script>

<style>
#app {
    
    
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39055970/article/details/123125129
今日推荐