demo.png
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
#app {
text-align: center;
color: #2c3e50;
width: 400px;
margin: 0 auto;
}
.title {
display: flex;
}
.title p {
width: 33%;
}
ul {
overflow: hidden;
width: 100%;
margin: 0 auto;
}
ul li {
box-sizing: border-box;
border: 1px solid #000;
width: calc(100% / 7);
height: 40px;
list-style: none;
float: left;
}
ul .today {
background-color: #e6001c;
color: #fff;
}
</style>
</head>
<body>
<div id="app">
<div class="title">
<p @click="prevMonth">上</p>
<p>{{year}}年{{month}}月</p>
<p @click="nextMonth">下</p>
</div>
<ul>
<li v-for="(item,index) in [1,2,3,4,5,6,'日']" :key="index+100">周{{item}}</li>
<li :class="{'today':today(year,month,item2.day)}"
v-for="(item2,index2) in visibleCalendar" :key="index2">{{item2.day}}</li>
</ul>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
year: 0,
month: 0,
visibleCalendar: [],
},
created() {
this.year = new Date().getFullYear()
this.month = new Date().getMonth() + 1 // getMonth()返回月份 (0 ~ 11)
this.visibleCalendar = this.constructCalendar(this.year, this.month)
},
methods: {
// 特殊标记今天
today(y, m, d) {
if (
y == new Date().getFullYear() &&
m == new Date().getMonth() + 1 &&
d == new Date().getDate()
) {
return true
}
return false
},
// 上个月
prevMonth() {
if (this.month == 1) {
this.month = 12
this.year -= 1
} else {
this.month -= 1
}
this.visibleCalendar = this.constructCalendar(this.year, this.month)
},
// 下个月
nextMonth() {
if (this.month == 12) {
this.month = 1
this.year += 1
} else {
this.month += 1
}
this.visibleCalendar = this.constructCalendar(this.year, this.month)
},
// 构造日历数据
constructCalendar(year, month) {
month -= 1
// 获取当月的天数
let monthDayNum = new Date(year, month + 1, 0).getDate()
// 获取当月第一天是星期几, getDay()返回一周中的某一天 (0 ~ 6) 周日:0
let weekDay = new Date(year, month, 1).getDay() || 7 // 把0变成7,以便计算前置空白
// 获取当月第一天的时间戳(毫秒)
let startTime = new Date(year, month, 1).getTime()
// 构造当月所有的日期
let calendatArr = []
// 用空数据填充当月第一天之前的空白
for (let i = 0; i < weekDay - 1; i++) {
calendatArr.push({
date: 0,
year: year,
month: month + 1,
day: "",
})
}
// 构造真实日期数据
for (let i = 0; i < monthDayNum; i++) {
calendatArr.push({
date: new Date(startTime + i * 24 * 60 * 60 * 1000),
year: year,
month: month + 1,
day: new Date(
startTime + i * 24 * 60 * 60 * 1000
).getDate(),
})
}
console.log(year + "-" + (month + 1))
console.log("当月第一天:周" + weekDay)
console.log("当月第一天:时间戳" + startTime)
console.log("当月天数:" + monthDayNum)
console.log(calendatArr)
return calendatArr
},
},
})
</script>
</body>
</html>
参考文章:https://www.jianshu.com/p/d8ce25e9badb
网友评论