Vue实现日历渲染

7次阅读

共计 1921 个字符,预计需要花费 5 分钟才能阅读完成。

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


<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 中的时间戳取得是本地时间戳, 如有需求请自行获取服务器端的时间戳.
如有其它不足, 还请提出修改意见.

正文完
 0