head要先引入vue:
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
html:
<div id="app">
<div class='data_header'>
<div class='prevBtn' @click='handlePrev'></div>
<div class="showData">{{year}}年{{month}}月{{day}}日</div>
<div class="nextBtn" @click='handleNext'></div>
</div>
<div class="week">
<div class="week-header">
<div>日</div>
<div>一</div>
<div>二</div>
<div>三</div>
<div>四</div>
<div>五</div>
<div>六</div>
</div>
<div class='week_day'>
<div v-for='i in 42'>
<div v-if='i-beginDay<= 0' class='other-day'>{{ prevMonthDays - beginDay + i }}</div>
<div v-else-if='i-beginDay > currentMonthDays' class='other-day'>{{i-beginDay-currentMonthDays}}</div>
<div v-else :class="{
'now-day':currentDay == `${year}-${month}-${i-beginDay}`,
'active-day':`${year}-${month}-${day}` == `${year}-${month}-${i-beginDay}`
}" :data-set="i-beginDay" @click='chosenDay'>{{i-beginDay}}</div>
</div>
</div>
</div>
</div>
<script>
new Vue({
el: "#app",
data: {
year: null,
month: null,
day: null,
currentDay: null
},
created() {
this.intiDate()
},
methods: {
intiDate() { // 当天的年月日
let date = new Date();
this.year = date.getFullYear()
this.month = date.getMonth() + 1
this.day = date.getDate()
this.currentDay = `${this.year}-${this.month}-${this.day}`
},
chosenDay(e) {
this.day = e.target.dataset.set
},
handlePrev() {
if (this.month === 1) {
this.month = 12
this.year--;
} else {
this.month--
}
},
handleNext() {
if (this.month === 12) {
this.month = 1
this.year++
} else {
this.month++
}
}
},
computed: {
beginDay() { //每个月第一天从星期几开始
return new Date(this.year, this.month - 1, 1).getDay()
},
prevMonthDays() { // 上一个月共有多少天
return new Date(this.year, this.month - 1, 0).getDate()
},
currentMonthDays() { // 当前这个月共有多少天
return new Date(this.year, this.month, 0).getDate()
}
}
})
</script>
css:
<style>
#app {
width: 500px;
margin-left: 100px;
}
.data_header {
width: 100%;
/* height:30px; */
line-height: 30px;
display: flex;
}
.prevBtn,
.nextBtn {
width: 0;
height: 0;
border: 15px solid transparent;
}
.prevBtn {
border-right-color: #007fff;
}
.nextBtn {
border-left-color: #007fff;
}
.showData {
flex: 1;
text-align: center;
color: #007fff;
}
.week-header {
display: flex;
background: #007fff;
}
.week-header div {
flex: 1;
text-align: center;
line-height: 30px;
color: #fff;
font-weight: 600;
}
.week_day {
display: flex;
flex-wrap: wrap;
}
.week_day>div {
width: 14.28%;
text-align: center;
line-height: 50px;
cursor: pointer;
}
.other-day {
color: #ccc;
}
.now-day {
background-color: #007fff;
color: #fff;
font-weight: 600;
}
.active-day:not(.now-day) {
color: #007fff;
border: 2px solid #007fff;
line-height: 46px;
}
</style>