需求制做一个签到日历,先简单的将日历的效果作出来,直接分享一下源码,有须要直接取用就好.数组
<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中的时间戳取得是本地时间戳,若有需求请自行获取服务器端的时间戳.
若有其它不足,还请提出修改意见.服务器