Vue+Element实现时间日期范围限定的两种方式

Element提供了时间日期选择器的UI组件,那么如去限制起止时间呢?这里提供两种方式。1)时间范围限制;2)时间起止时间限定。

1、时间范围限制

限定时间范围,超出范围,弹出提示,并且清空iinput内容,如图所示:

界面:

style="width:100%;max-width: 300px" value-format="yyyy-MM-dd" @change="handleStartDateChange">

方法:

data() {

return {

startDate: '',

},

methods: {

handleStartDateChange() {

if (this.startDate && this.startDate.length > 0) {

const timestampBegin = +new Date(this.startDate[0])

const timestampEnd = +new Date(this.startDate[1])

if (timestampEnd > timestampBegin + 3600 * 1000 * 24 * 10) {

this.$alert('日期的起止时间跨度不能超过10天', '提示', {

confirmButtonText: '确定',

type: 'warning'

})

.then(() => (this.startDate = null))

.catch(() => (this.startDate = null))

}

}

},

}

2) 时间起止时间限定

先选的日期会限制后选的时间,如果先选起始时间,就会限制终止时间的选择,反之,终止时间限制起始时间的选择,如图所示:

界面:

:picker-options="pickerOptionsStart">

:picker-options="pickerOptionsEnd">

方法:

queryDay: 10就是控制起止日期的范围大小,这里可选范围是10天

data() {

return {

deskStartDate: '',

deskEndDate: '',

queryDay: 10,

pickerOptionsStart: {

disabledDate: time => {

if (this.deskEndDate) {

return time.getTime() > new Date(this.deskEndDate).getTime() || time.getTime() < new Date(this.deskEndDate).getTime() -

this.queryDay * 24 * 60 * 60 * 1000

}

}

},

pickerOptionsEnd: {

disabledDate: time => {

if (this.deskStartDate) {

return time.getTime() < new Date(this.deskStartDate).getTime() || time.getTime() > new Date(

this.deskStartDate).getTime() + this.queryDay * 24 * 60 * 60 * 1000

}

}

}

}

}