业务场景: elementUI日期时间控件只允许选择大于当前时间的时间;
实现方式:
:picker-options="{
disabledDate:(time)<new Date()-8.64e7
//控制选择时间在今天之后(-8.64e7代表可以选择今天)
selectableRance:this.startTimeRange
//控制选择时间在当前设置的范围中,该字段是一个字符串
}"
:default-time=startTime//控制打开弹框后默认选择的开始时间为当前时间
控件上用v-model进行数据绑定,获得所选的最新值,利用watch监听值
updateTime: {
handler(newValue) {
if (newValue) {
let nowDate = this.format(new Date(), "-");
let dt = nowDate.split(" ");
let st = "";
if (newValue.split(" ")[0] === dt[0]) {
// 是今天,选择 的时间开始为此刻的时分秒
st = dt[1];
if(newValue.split(" ")[1]==="00:00:00"){
newValue=dt[0]+' '+dt[1]
//由于默认选择时间是00:00:00,当日所选时间为00:00:00的情况下,将时间修改为当前时间
}
} else {
// 明天及以后从0时开始
st = "00:00:00";
}
this.updateTime=newValue
// 拼接拿到不同日期的默认时间
this.startTimeRange = st + " - 23:59:59";
//进行时间选择范围的设置
//例如:如果今天此刻时间为10:41:40 则选择时间范围为: 10:41:40 - 23:59:59
//否则为:00:00:00- 23:59:59
}
},
日期时间转换函数
format(Date, str) {
var obj = {
Y: Date.getFullYear(),
M: Date.getMonth() + 1,
D: Date.getDate(),
H: Date.getHours(),
Mi: Date.getMinutes(),
S: Date.getSeconds(),
};
// 拼接时间 hh:mm:ss
var time =
" " +
this.supplement(obj.H) +
":" +
this.supplement(obj.Mi) +
":" +
this.supplement(obj.S);
// yyyy-mm-dd
if (str.indexOf("-") > -1) {
return (
obj.Y +
"-" +
this.supplement(obj.M) +
"-" +
this.supplement(obj.D) +
time
);
}
// yyyy/mm/dd
if (str.indexOf("/") > -1) {
return (
obj.Y +
"/" +
this.supplement(obj.M) +
"/" +
this.supplement(obj.D) +
time
);
}
},
时间不是两位数的第一位用零占位
supplement(nn) {
return (nn = nn < 10 ? "0" + nn : nn);
},