需求製做一個簽到日曆,先簡單的將日曆的效果作出來,直接分享一下源碼,有須要直接取用就好.數組
<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中的時間戳取得是本地時間戳,若有需求請自行獲取服務器端的時間戳.
若有其它不足,還請提出修改意見.服務器