使用element组件
view层
<el-date-picker
v-model="dataValue.value1"
type="month"
placeholder="选择月"
:clearable="false"
@change="getValue1(dataValue.value1)"
>
</el-date-picker
>至
<el-date-picker
class="picker2"
v-model="dataValue.value2"
type="month"
placeholder="选择月"
:clearable="false"
@change="getValue2(dataValue.value2)"
>
</el-date-picker>
data中赋值,实现初始默认为当前月到之前3个月,例如2024-05-01到2024-07-31
const now = new Date();
const currentMonthLastDay = new Date(
now.getFullYear(),
now.getMonth() + 1,
0
).getTime(); // 当前月的最后一天
const threeMonthsAgoFirstDay = new Date(
now.getFullYear(),
now.getMonth() - 2,
1
).getTime(); // 三个月前的1号
把这个两个值,分别赋给
dataValue: {
value1: threeMonthsAgoFirstDay,
value2: currentMonthLastDay,
},
methods层,首先监听并得到月份,至于日是不对的,我们需要 this.dataValue.value2为最后一日
getValue1(newVal) {
this.updateValue2(newVal);
},
getValue2(newVal) {
this.updateValue1(newVal);
},
updateValue2(newValue1) {
const newDate = new Date(newValue1);
newDate.setMonth(newDate.getMonth() + 3);
newDate.setDate(0);
this.dataValue.value2 = newDate.getTime();
},
updateValue1(newValue2) {
const newDate = new Date(newValue2);
newDate.setMonth(newDate.getMonth() - 2);
this.dataValue.value1 = newDate.getTime();
},
在使用接口传递数据时,应该进行操作一下
startDate: formatDate(
new Date(this.dataValue[0]).getTime(),
"yyyy-MM-01 00:00:00"
),
endDate: this.formatEndDate(new Date(this.dataValue[1])),
具体操作,使用这个方法即可实现获取最后一日。
//获取年
getYearMonthFromTimestamp(timestamp) {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = date.getMonth() + 1;
return { year, month };
},
//获取月
getLastDayOfMonth(year, month) {
return new Date(year, month, 0).getDate();
},
//获取最后一日
formatEndDate(date) {
const yearMonth = this.getYearMonthFromTimestamp(date);
const lastDay = this.getLastDayOfMonth(yearMonth.year, yearMonth.month);
return `${yearMonth.year}-${String(yearMonth.month).padStart(
2,
"0"
)}-${lastDay} 23:59:59`;
},