Vue:自定义实现日历表

Vue:自定义实现日历表,第1张

简介

学习了一下关于如何自定义一个日历表。
参考文章:Vue写一个日历

具体实现 第一步:打开windows的日历

可以看到,有如下关键点(暂时忽略农历、节气、节日的备注信息):
①年月的信息;
②上一个月、下一个月的快捷切换按钮;
③周一到周天的行;
④深颜色的当前月日期;
⑤填充空白的灰色日期(其他月的日期信息);

第二步:分析

①计算出显示月份的天,并显示;
②切换月份时,重新执行①;
③月初、月末的星期几的空白日,需要上一个月下一个月的对应天数补齐;
④第一次显示时,今天日期的选中。

第三步:了解需要使用到的日期API
getFulleYear(); // 年
getMonth(); // 月, 0-11
getDate();  // 日,也就是几号
getDay();   // 星期几,0-6
new Date(2019,2,10);  // 实际上就是 2019-03-10
new Date(2019,2,0);   // 实际上是 2019-02-28, 也就是2月份的最后一天
new Date(2019,2,-1);  // 实际上是 2019-02-27, 也就是2月份的倒数第二天

var d = new Date();
d.setTime( new Date(2018,1,1).getTime() );   
d.getFullYear();   // 2018 , setTime 允许传入毫秒数来更改实例对象
第四步:代码实现
<template>
  <div class="calendar-box">
    <div class="calendar-wrapper">
      <div class="calendar-toolbar">
        <div class="prev" @click="prevMonth">上个月</div>
        <div class="current">{{ currentDateStr }}</div>
        <div class="next" @click="nextMonth">下个月</div>
      </div>

      <div class="calendar-week">
        <div
          class="week-item calendarBorder"
          v-for="item of weekList"
          :key="item"
        >
          {{ item }}
        </div>
      </div>
      <div class="calendar-inner">
        <div
          class="calendar-item calendarBorder"
          v-for="(item, index) of calendarList"
          :key="index"
          :class="{
            'calendar-item': true,
            calendarBorder: true,
            'calendar-item-hover': !item.disable,
            'calendar-item-disabled': item.disable,
            'calendar-item-checked':
              dayChecked && dayChecked.value == item.value,
          }"
          @click="handleClickDay(item)"
        >
          {{ item.date }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showYearMonth: {}, // 显示的年月
      calendarList: [], // 用于遍历显示
      shareDate: new Date(), // 享元模式,用来做 日期数据转换 优化
      dayChecked: {}, // 当前选择的天
      weekList: ["一", "二", "三", "四", "五", "六", "日"], // 周
    };
  },
  created() {
    this.initDataFun(); // 初始化数据
  },
  computed: {
    // 显示当前时间
    currentDateStr() {
      let { year, month } = this.showYearMonth;
      return `${year}${this.pad(month + 1)}`;
    },
  },
  methods: {
    //#region 计算日历数据
    // 初始化数据
    initDataFun() {
      // 初始化当前时间
      this.setCurrentYearMonth(); // 设置日历显示的日期(年-月)
      this.createCalendar(); // 创建当前月对应日历的日期数据
      this.getCurrentDay(); // 获取今天
    },
    // 设置日历显示的日期(年-月)
    setCurrentYearMonth(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.showYearMonth = {
        year,
        month,
        date,
      };
    },
    getCurrentDay(d = new Date()) {
      let year = d.getFullYear();
      let month = d.getMonth();
      let date = d.getDate();
      this.dayChecked = {
        year,
        month,
        date,
        value: this.stringify(year, month, date),
      };
    },
    // 创建当前月对应日历的日期数据
    createCalendar() {
      // 一天有多少毫秒
      const oneDayMS = 24 * 60 * 60 * 1000;

      let list = [];
      let { year, month } = this.showYearMonth;
      // #region
      // ---------------仅仅只算某月的天---------------
      //   // 当前月,第一天和最后一天的毫秒数
      //   let begin = new Date(year, month, 1).getTime();
      //   let end = new Date(year, month + 1, 0).getTime();

      // ---------------计算某月前后需要填补的天---------------
      // 当前月份第一天是星期几, 0-6
      let firstDay = this.getFirstDayByMonths(year, month);
      // 填充多少天,因为我将星期日放到最后了,所以需要另外调整下
      let prefixDaysLen = firstDay === 0 ? 6 : firstDay - 1;
      // 向前移动之后的毫秒数
      let begin = new Date(year, month, 1).getTime() - oneDayMS * prefixDaysLen;
      // 当前月份最后一天是星期几, 0-6
      let lastDay = this.getLastDayByMonth(year, month);
      // 填充多少天,因为我将星期日放到最后了,所以需要另外调整下
      let suffixDaysLen = lastDay === 0 ? 0 : 7 - lastDay;
      // 向后移动之后的毫秒数
      let end =
        new Date(year, month + 1, 0).getTime() + oneDayMS * suffixDaysLen;
      // 计算左侧时间段的循环数
      let rowNum = Math.ceil((end - begin) / oneDayMS / 7);
      let newPeriod = [];
      for (let i = 0; i < rowNum; i++) {
        newPeriod.push({});
      }
      // #endregion
      // 填充天
      while (begin <= end) {
        // 享元模式,避免重复 new Date
        this.shareDate.setTime(begin);
        let year = this.shareDate.getFullYear();
        let curMonth = this.shareDate.getMonth();
        let date = this.shareDate.getDate();
        list.push({
          year: year,
          month: curMonth + 1, // 月是从0开始的
          date: date,
          value: this.stringify(year, curMonth, date),
          disable: curMonth !== month,
        });
        begin += oneDayMS;
      }

      this.calendarList = list;
    },
    // 格式化时间,与主逻辑无关
    stringify(year, month, date) {
      let str = [year, this.pad(month + 1), this.pad(date)].join("-");
      return str;
    },
    // 对小于 10 的数字,前面补 0
    pad(str) {
      return str < 10 ? `0${str}` : str;
    },
    // 点击上一月
    prevMonth() {
      this.showYearMonth.month--;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围, 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 点击下一月
    nextMonth() {
      this.showYearMonth.month++;
      this.recalculateYearMonth(); // 因为 month的变化 会超出 0-11 的范围, 所以需要重新计算
      this.createCalendar(); // 创建当前月对应日历的日期数据
    },
    // 重算:显示的某年某月
    recalculateYearMonth() {
      let { year, month, date } = this.showYearMonth;

      let maxDate = this.getDaysByMonth(year, month);
      // 预防其他月跳转到2月,2月最多只有29天,没有30-31
      date = Math.min(maxDate, date);

      let instance = new Date(year, month, date);
      this.setCurrentYearMonth(instance);
    },
    // 判断当前月有多少天
    getDaysByMonth(year, month) {
      return new Date(year, month + 1, 0).getDate();
    },
    // 当前月的第一天是星期几
    getFirstDayByMonths(year, month) {
      return new Date(year, month, 1).getDay();
    },
    // 当前月的最后一天是星期几
    getLastDayByMonth(year, month) {
      return new Date(year, month + 1, 0).getDay();
    },
    // #endregion 计算日历数据

    //  *** 作:点击了某天
    handleClickDay(item) {
      if (!item || item.disable) return;
      console.log(item);
      this.dayChecked = item;
    },
  },
};
</script>

<style lang="less" scoped>
@calendarWidth: 637px; // 90 * 7 + 7 * 1
.calendar-box {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  .calendar-wrapper {
    .calendar-toolbar {
      width: @calendarWidth;
      height: 50px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .prev,
      .next,
      .current {
        cursor: pointer;
        &:hover {
          color: #438bef;
        }
      }
    }
    .calendar-week {
      width: @calendarWidth;
      border-left: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      .week-item {
        width: 90px;
        height: 50px;
        border-top: 1px solid #eee;
      }
    }
    .calendar-inner {
      width: @calendarWidth;
      border-left: 1px solid #eee;
      display: flex;
      flex-wrap: wrap;
      .calendar-item {
        width: 90px;
        height: 60px;
      }
      .calendar-item-hover {
        cursor: pointer;
        &:hover {
          color: #fff;
          background-color: #438bef;
        }
      }
      .calendar-item-disabled {
        color: #acacac;
        cursor: not-allowed;
      }
      .calendar-item-checked {
        color: #fff;
        background-color: #438bef;
      }
    }
    .calendarBorder {
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 1px solid #eee;
      border-right: 1px solid #eee;
    }
  }
}
</style>

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1322026.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存