在使用el-date-picker时,想要以下需求:
- 选中第一个日期后(如:12月15日),第二个日期=第一个日期-7,或者第二个日期=第一个日期+7,即第二个日期选择范围如图:(前后7天可选)
- 只能选择今天以及今天之前的日期。
javascript
<el-date-picker
v-model="value"
type="daterange"
range-separator="到"
start-placeholder="开始时间"
end-placeholder="结束时间"
value-format="YYYY-MM-DD"
@change="change"
:disabled-date="disabledDate"
@calendar-change="handleChange"
@focus="handleFocus"
:clearable="false"
/>
javascript
const pickDay = ref()
const handleFocus = () => {
pickDay.value = null
}
const limitTime = 1000 * 60 * 60 * 24 * 6
const disabledDate = (time: Date) => {
if (pickDay.value) {
return (
time.getTime() < pickDay.value.getTime() - limitTime ||
time.getTime() > pickDay.value.getTime() + limitTime ||
time.getTime() > Date.now()
)
} else {
return time.getTime() > Date.now()
}
}
const handleChange = (val: Date[]) => {
const [pointDay] = val
pickDay.value = pointDay
}
或者使用dayJs,disabledDate
可以改为
javascript
import dayjs from 'dayjs'
const disabledDateSeven = (time: Date) => {
if (pickDay?.value) {
return (
time.getTime() < dayjs(pickDay.value.getTime()).subtract(6, 'day') ||
time.getTime() > dayjs(pickDay.value.getTime()).add(6, 'day') ||
time.getTime() > Date.now()
)
} else {
return time.getTime() > Date.now()
}
}