Vue完成日历衬着

需求制造一个签到日历,先简朴的将日历的结果做出来,直接分享一下源码,有须要直接取用就好.

<template>
  <div>
    <!-- 日历头 -->
    <div class="calenderTitle">
      <div class="calenderItem" v-for="item of calenderTitel">{{item}}</div>
    </div>
    <!-- 日历内容 -->
    <div class="calenderInside">
      <div class="calenderItem" v-for="item of calenderArray">{{item}}</div>
    </div>
  </div>
</template>

<style>
// 完成每行7个自动换行
.calenderTitle, .calenderInside{
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  width: 700px;
}
.calenderItem{
  width: 100px;
  height: 100px;
}
</style>

<script>
export default {
  data () {
    return {
      // 猎取当前时候戳(后期采纳服务器时候)
      timestamp: (new Date()).getTime(),
      // 当前年份
      nowYear: null,
      // 当前月份
      nowMonth: null,
      // 当前日期
      nowDate: null,
      // 当前礼拜
      nowDay: null,
      // 日期题目
      calenderTitel: ['日', '一', '二', '三', '四', '五', '六'],
      // 日期内容
      calenderArray: []
    }
  },
  methods: {
    // 拆分年月日礼拜
    getNowDate () {
      // 将时候戳转换为日期对象
      const theTime = typeof (timestamp) === 'object' ? this.timestamp : new Date(this.timestamp)
      this.nowYear = theTime.getFullYear()
      this.nowMonth = theTime.getMonth() + 1
      this.nowDate = theTime.getDate()
      this.nowDay = theTime.getDay() // 礼拜日为0,其他礼拜对应数值
      this.getFirstDay()
    },
    getFirstDay () {
      let firstDayWeek = null
      // 猎取当月1号的礼拜
      firstDayWeek = new Date(this.nowYear + '/' + this.nowMonth + '/' + '01').getDay()
      console.log('当前月份1号的礼拜')
      console.log(firstDayWeek)
      // 当月天数
      let nowMonthDay = this.getNowMonthDay(this.nowYear, this.nowMonth)
      console.log('nowMonthDay')
      console.log(nowMonthDay)
      let arr = []
      // 依据当月1号的礼拜数来给衬着数组前面增加对应数目的空格
      for (let indexEmpty = 0; indexEmpty < parseInt(firstDayWeek); indexEmpty++) {
        arr.push('')
      }
      // 经由过程函数推断当前月份有若干天,并依据天数添补衬着数组
      for (let indexNum = 1; indexNum < nowMonthDay + 1; indexNum++) {
        arr.push(indexNum)
      }
      // 深拷贝日历衬着数组(因为后期可能会改成签到日历,数组的每一项多是object所以深拷贝)
      this.calenderArray = JSON.parse(JSON.stringify(arr))
    },
    // 盘算当前年份是不是为闰年
    isLeapYear (year) {
      return (year % 400 === 0 || year % 4 === 0) && year % 100 !== 0
    },
    // 盘算当前月份有若干天
    getNowMonthDay (year, month) {
      return [null, 31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (this.isLeapYear(year) ? 29 : 28)
    }
  },
  created () {
    // 将时候戳转换拆分为详细数值
    this.getNowDate()
  }
}
</script>

有些全局变量关于纯真的日历没有太多用途,能够将其变成局部变量经由过程参数通报.
Demo中的时候戳获得是当地时候戳,若有需求请自行猎取服务器端的时候戳.
若有别的不足,还请提出修改意见.

    原文作者:SenHan
    原文地址: https://segmentfault.com/a/1190000019110598
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞