好用的日历控件
传入参数date如:new Date()
<template>
<div class="calendar">
<div class="week-box">
<span v-for="item in day" class="color-999999 font-14">{{item}}</span>
</div>
<div>
<div v-for="item in calendarData" class="xy-calendar-module">
<span v-for="day in item" class="box color-666666">{{day.day}}</span>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
date: {
type: Date,
default: new Date()
}
},
data() {
return {
day: ['日', '一', '二', '三', '四', '五', '六'],
calendarData: [],
nowYear: new Date().getFullYear(),
nowMonth: new Date().getMonth() + 1,
nowDay: new Date().getDate(),
}
},
mounted () {
if (!!this.$props.date) {
this.setDate();
}
this.initData(this.nowYear, this.nowMonth);
},
watch: {
date (val) {
this.setDate();
this.initData(this.nowYear, this.nowMonth);
}
},
methods: {
setDate () {
this.nowYear = new Date(this.$props.date).getFullYear()
this.nowMonth = new Date(this.$props.date).getMonth() + 1
this.nowDay = new Date(this.$props.date).getDate()
},
initData (year,month) {
const days = this.days(year,month); // 当前月份天数
let enableSelect;
let arr = Array.from({length: days}, (x, index )=>index + 1).map(item => {
return {
day: item,
name: this.getDayName(year, month, item),
week: this.getDateWeek(year, month, item)
}
});
// 最前边是星期一
let beforeDayNum = arr[0].week - 1;
let afterDayNum = 7 - arr[days-1].week;
// 最前边是星期日
let beforeDayNum = arr[0].week == 7 ? 0 : arr[0].week;
let afterDayNum = 6 - arr[days-1].week == -1 ? 6 : 6 - arr[days-1].week;
var beforeDayArr = this.completionDays(beforeDayNum);
var afterDayArr = this.completionDays(afterDayNum);
var allArr = [...beforeDayArr, ...arr, ...afterDayArr];
this.calendarData = this.splitArray(allArr);
console.log(afterDayNum)
},
splitArray (arr) {
var result = [];
for(var i=0; i < arr.length; i+=7){
result.push(arr.slice(i,i+7));
}
return result
},
completionDays (num) {
return Array.from({length: num}, (x, index )=>index + 1).map(item => {
return {
day: null,
week: null
}
})
},
// 一个月多少天
days(year,month){
var dayCount;
let now = new Date(year,month, 0);
dayCount = now.getDate();
return dayCount;
},
// 某一天星期几
getDateWeek (year,month,day) {
var tmpdate = new Date(year,month-1,day).getDay();
return tmpdate === 0 ? 7 : tmpdate;
},
getToday () {
let nowYear = new Date().getFullYear();
let nowMonth = new Date().getMonth() + 1;
let nowDay = new Date().getDate();
return {
nowYear,
nowMonth,
nowDay
}
},
getDayName (year, month, day) {
if (year == this.getToday().nowYear && month == this.getToday().nowMonth && day == this.getToday().nowDay) {
return '今天'
}
return `${day}`
}
}
}
</script>
<style scoped>
.calendar{
margin: 0 auto;
background: #FFFFFF;
}
.xy-calendar-module{
position: relative;
display: flex;
height: .44rem;
line-height: .44rem;
}
.box{
flex: 1;
position: relative;
text-align: center;
}
.week-box{
display: flex;
height: .44rem;
line-height: .44rem;
}
.week-box span{
flex: 1;
text-align: center;
}
</style>

浙公网安备 33010602011771号