最近使用vue和原生Date对象api写了一个日历,具体样式如下:
由于是原生Date对象的api,所以需要封装函数向前减或向后加number天
// 用来编辑日期,向前减或向后加number天
editDate(date, type = "add", number = 1) {
const types = type === 'add' ? 1 : -1
const dates = date.getDate()
const newDate = new Date(date)
newDate.setDate(dates + number * types)
return newDate
}
初始化一个数组用以保存每个日历页面的所有日期
// 初始化一个数据用来保存每页日历的所有日期天数
canlender = []
init(date = new Date()) {
// 把当前日期定位到一号
const currentDate = new Date(date)
currentDate.setDate(1)
// 获取当前年月
this.year = currentDate.getFullYear()
this.month = currentDate.getMonth()
// 获取星期
const currentWeek = currentDate.getDay()
// 第一排放入一号的日期
this.canlender.push({
date: this.formatDate(currentDate),
dateNum: currentDate.getDate()
})
// 根据一号的日期向前补齐
for (let i = 0; i < currentWeek; i++) {
const date = this.editDate(currentDate, 'sub', i + 1)
this.canlender.unshift({
date: this.formatDate(date),
dateNum: date.getDate()
})
}
// 根据一号日期向后补齐,总共放六周日期
for (let i = 1; i < 42 - currentWeek; i++) {
const date = this.editDate(currentDate, 'add', i)
this.canlender.push({
date: this.formatDate(date),
dateNum: date.getDate()
})
}
}
vue部分的代码:
<template>
<div class="canlender">
<div class="title">
<!-- 上一月 -->
<div class="left btn" @click="editMonth('sub')"></div>
<div class="date-title">{{ dateFormat }}</div>
<!-- 下一月 -->
<div class="right btn" @click="editMonth('add')"></div>
</div>
<!-- 存放星期标题 -->
<div class="week-day">
<div v-for="i in weekDay" :key="i">{{ i }}</div>
</div>
<!-- 日期容器 -->
<div class="date-container">
<div v-for="item in canlender" :key="item.date">
{{ item.dateNum }}
</div>
</div>
</div>
</template>
// ...
// ...
<script>
data() {
return {
msg: [],
weekDay: ["日", "一", "二", "三", "四", "五", "六"],
canlenderObj: null,
canlender: [],
currentDate: new Date(),
};
},
methods: {
// 切换到上一个月或者下一个月
editMonth(type) {
const num = type === "sub" ? -1 : 1;
this.currentDate.setMonth(this.currentDate.getMonth() + num);
// 清空canlender日期容器
this.canlenderObj.clear();
// 重新生成canlender日期容器
this.canlenderObj.init(this.currentDate);
this.canlender = this.canlenderObj.canlender;
},
},
computed: {
dateFormat() {
return this.canlenderObj
? this.canlenderObj.year + "年" + (this.canlenderObj.month + 1) + "月"
: "";
},
},
</script>
好啦,这样一个简单的日历就完成啦
日历.gif