如题:element ui 开始时间和结束时间,时间限制,带年月日时分秒
最终样子:
template部分:
<el-form-item label="时间" label-width="90px">
<el-date-picker
v-model="searchCond.startTime"
type="datetime"
placeholder="开始时间"
:clearable="false"
value-format="yyyy-MM-dd HH:mm:ss"
:picker-options="pickerOptionsStart"
/>
<span style="padding: 0 3px; color: #000"> 至 </span>
<el-date-picker
v-model="searchCond.endTime"
type="datetime"
:clearable="false"
placeholder="结束时间"
value-format="yyyy-MM-dd HH:mm:ss"
:picker-options="pickerOptionsEnd"
/>
</el-form-item>
data部分
//一个月
// 开始结束日期限制
pickerOptionsStart: {
selectableRange: '00:00:00 - 23:59:59',
disabledDate: (time) => {
if (this.searchCond.endTime) {
return (
time.getTime() > new Date(this.searchCond.endTime).getTime() ||
time.getTime() <
new Date(this.searchCond.endTime).getTime() -
1000 * 60 * 60 * 24 * 31
)
}
}
},
// 结束日期限制
pickerOptionsEnd: {
selectableRange: '00:00:00 - 23:59:59',
disabledDate: (time) => {
if (this.searchCond.startTime) {
return (
time.getTime() < new Date(this.searchCond.startTime).getTime() ||
time.getTime() >
new Date(this.searchCond.startTime).getTime() +
1000 * 60 * 60 * 24 * 30
)
}
}
}
js部分(添加监听):
watch: {
'searchCond.endTime': {
handler(newValue, oldValue) {
if (newValue) {
let timeST = ''
let st = ''
if (this.searchCond.startTime) {
const date = new Date(this.searchCond.startTime)
//此处用到moment插件,可自行安装此插件或者类似的插件即可
const nowDate = this.$moment(date).format('HH:mm:ss')
if (
this.$moment(date).format('yyyy-MM-DD') ===
this.$moment(newValue).format('yyyy-MM-DD')
) {
const hh1 = this.$moment(newValue).format('HH:mm:ss')
if (hh1 < nowDate) {
this.searchCond.endTime = new Date(this.searchCond.startTime)
}
st = nowDate
timeST = nowDate
} else {
st = '00:00:00'
timeST = '23:59:59'
}
} else {
st = '00:00:00'
timeST = '23:59:59'
}
this.pickerOptionsStart.selectableRange = '00:00:00 - ' + timeST
this.pickerOptionsStart = this.pickerOptionsStart
this.pickerOptionsEnd.selectableRange = st + ' - 23:59:59'
this.pickerOptionsEnd = this.pickerOptionsEnd
}
},
deep: true,
immediate: true
},
'searchCond.startTime': {
handler(newValue, oldValue) {
if (newValue) {
let timeST = ''
let st = ''
if (this.searchCond.endTime) {
const date = new Date(this.searchCond.endTime)
const nowDate = this.$moment(date).format('HH:mm:ss')
if (
this.$moment(date).format('yyyy-MM-DD') ===
this.$moment(newValue).format('yyyy-MM-DD')
) {
const hh1 = this.$moment(newValue).format('HH:mm:ss')
if (hh1 > nowDate) {
this.searchCond.startTime = new Date(this.searchCond.endTime)
}
st = nowDate
timeST = nowDate
} else {
st = '00:00:00'
timeST = '23:59:59'
}
} else {
st = '00:00:00'
timeST = '23:59:59'
}
this.pickerOptionsStart.selectableRange = '00:00:00 - ' + timeST
this.pickerOptionsStart = this.pickerOptionsStart
this.pickerOptionsEnd.selectableRange = st + ' - 23:59:59'
this.pickerOptionsEnd = this.pickerOptionsEnd
}
},
deep: true,
immediate: true
}
},