<ul class="date">
<li v-for="(item, index) in list" :key="index" :class="{'bg-color': item.y === year && item.m === month && item.d === day}">
<div class="day" :class="{'text-color': item.cur}">{{item.d}}</div>
<div>哈哈</div>
</li>
</ul>

data () {
return {
year: new Date().getFullYear(), // 今日年份
month: new Date().getMonth() + 1, // 今日月份
day: new Date().getDate(), // 今日日份
currentYear: '', // 当前显示年份
currentMonth: '', // 当前显示月份 0-11,显示时加一
currentDay: '', // 当前显示日份
monthDays: [], // 1-12月的天数
list: []
}
},
mounted () {
this.showCalender()
},
methods: {
isLeap (year) { // 判断是不是闰年
return (year % 100 === 0 ? (year % 400 === 0 ? 1 : 0) : (year % 4 === 0 ? 1 : 0))
},
showCalender (type) {
this.list = []
this.newDate = new Date()
if (!type) this.currentYear = this.newDate.getFullYear()
if (!type) this.currentMonth = this.newDate.getMonth()
this.monthDays = [31, 28 + this.isLeap(this.currentYear), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
this.currentDay = this.newDate.getDate()
this.firstDay = new Date(`${this.currentYear}-${this.currentMonth + 1}-1`)
this.firstnow = this.firstDay.getDay() // 当月第一日是星期几 1-7
if (this.firstnow === 0) this.firstnow = 7
if (this.firstnow > 1) {
// 前一个月份
let monIndex = this.currentMonth
let year
if (monIndex === 0) {
year--
monIndex = 11
} else {
monIndex--
}
for (let i = 0; i < this.firstnow - 1; i++) {
this.list.unshift({
y: year,
m: monIndex + 1,
d: this.monthDays[monIndex] - i
})
}
}
for (let i = 0; i < this.monthDays[this.currentMonth]; i++) {
// 当前月份
this.list.push({
y: this.currentYear,
m: this.currentMonth + 1,
d: i + 1,
cur: true
})
}
const num = (this.monthDays[this.currentMonth] + this.firstnow - 1) % 7
if (num > 0) {
// 下个月份
let monIndex2 = this.currentMonth
let year2
if (monIndex2 === 11) {
year2++
monIndex2 = 0
} else {
monIndex2++
}
for (let i = 0; i < 7 - num; i++) {
this.list.push({
y: year2,
m: monIndex2 + 1,
d: i + 1
})
}
}
},
preMon () {
if (this.currentMonth === 0) {
this.currentYear--
this.currentMonth = 11
} else {
this.currentMonth--
}
this.showCalender('pre')
},
nextMon () {
if (this.currentMonth === 11) {
this.currentYear++
this.currentMonth = 0
} else {
this.currentMonth++
}
this.showCalender('next')
}


// scss 只放了表格样式
ul{
display: flex;
justify-content: space-around;
flex-wrap: wrap;
align-items: center;
border-top: 1rpx solid #E9E9E9;
border-left: 1rpx solid #E9E9E9;
li{
flex-grow: 1;
min-width: 44px;
height: 50px;
border-bottom: 1rpx solid #E9E9E9;
border-right: 1rpx solid #E9E9E9;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
color: #999;
font-size: 12px;
.day{
margin-bottom: 6px;
}
.text-color{
color: #222;
}
&.bg-color{
background-color: #E9E9E9;
}
}
}