需求:实现点击1个月、3个月、6个月的时候,el-date-picker 控件分别显示当前月、当前月-3、当前月-6;
举例:当前月为2023-08,那么点击1个月时显示2023-08至2023-08,点击3个月显示2023-05至2023-08
点击6个月显示2023-02至2023-08
HTML部分:
<div class="button">
<el-button type="primary" @click="getMonthDate(1)">1个月</el-button>
<el-button type="primary" @click="getMonthDate(3)">3个月</el-button>
<el-button type="primary" @click="getMonthDate(6)">6个月</el-button>
</div>
JS部分:
getMonthDate(time) {
let year = new Date().getFullYear();
let curMonth = new Date().getMonth() + 1;
let month = curMonth >= 10 ? curMonth : "0" + curMonth
if (time === 1) {
this.searchTimes[0] = `${year}-${month}`;
this.searchTimes[1] = `${year}-${month}`;
}
if (time === 3) {
let oneMonth = curMonth - 3;
this.searchTimes[0] = this.getDate(oneMonth);
this.searchTimes[1] = `${year}-${month}`;
}
if (time === 6) {
let oneMonth = curMonth - 6;
this.searchTimes[0] = this.getDate(oneMonth);
this.searchTimes[1] = `${year}-${month}`;
}
},
getDate(month) {
let date = new Date();
let year = date.getFullYear();
let newYear = 0;
let newMonth = 0;
if (month < 1) {
newYear = year - 1;
newMonth = month + 12 >= 10 ? month + 12 : '0' + (month + 12);
return newYear + '-' + newMonth;
} else {
newMonth = month >= 10 ? month : '0' + (month);
return year + '-' + newMonth;
}
}