项目中有个需求,开始时间选中后,结束时间自动填充成30天后的时间<当然,如果30天后的时间比当前时间大,那么填充当前时间到结束时间>。结束时间选中时,开始时间自动填充为结束时间的前30天
效果如下图所示:
代码如下:
1.html部分
--
2.data部分
query: {
startDate: '',// 开始日期,显示在弹框里的
endDate: '', // 结束日期,显示在弹框里的
endDateNow: '', // 当前日期,如果30天后的日期大于当前日期,要显示当前日期
},
3.创建组件时,给2中的data部分变量赋值时间为当前时间
created() {
const date = new Date()
this.query.startDate = moment(date).format('YYYY-MM-DD') // 开始时间
this.query.endDate = moment(date).format('YYYY-MM-DD') // 结束时间
this.query.endDateNow = moment(date).format('YYYY-MM-DD') // 当前结束时间
},
4.当选中时间发生变化时, methods部分
methods: {
/**
* 获取当前时间前几天或后几天时间
* @param today 当前时间
* @param day day为number,getDay(-1):昨天的日期;getDay(0):今天的日期;getDay(1):明天的日期;【以此类推】
* @returns {string}
*/
getDay(today, day) {
// var today = new Date();
const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
today.setTime(targetday_milliseconds); // 注意,这行是关键代码
const tYear = today.getFullYear();
let tMonth = today.getMonth();
let tDate = today.getDate();
tMonth = this.doHandleMonth(tMonth + 1);
tDate = this.doHandleMonth(tDate);
return tYear + '-' + tMonth + '-' + tDate;
},
doHandleMonth(month) {
var m = month;
if (month.toString().length == 1) {
m = '0' + month;
}
return m;
},
// 开始时间点击
handleStart() {
const oDate1 = new Date(this.getDay(new Date(this.query.startDate), 30)) // 选中的开始时间后30天
const oDate2 = new Date() // 当前时间
if (oDate1.getTime() > oDate2.getTime()) { // 如果30天后时间比前时间大,显示当前时间
this.query.endDate = this.query.endDateNow
} else { // 否则显示选中开始时间30天后的时间
this.query.endDate = this.getDay(new Date(this.query.startDate), 30)
}
},
// 结束时间点击
handleEnd() {
this.query.startDate = this.getDay(new Date(this.query.endDate), -30) // 结束时间选中后,开始时间显示结束时间前30天
}
}