Open klren0312 opened 3 years ago
<template>
<el-date-picker
v-model="dateRange"
type="daterange"
placeholder="选择日期时间"
:picker-options="weekOption"
:editable="false"
:clearable="false"
format="yyyy-MM-dd"
value-format="yyyy-MM-dd"
size="small"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
>
</el-date-picker>
</template>
<script>
export default {
name: 'WeekSelect',
props: {
dates: {
// 当前选择的起始结束日期数组
type: Array,
default: () => ['', '']
},
showToday: {
// 是否可选今天
type: Boolean,
default: false
}
},
model: {
prop: 'dates',
event: 'update'
},
data() {
return {
startDate: '',
weekOption: {
firstDayOfWeek: 1,
disabledDate: date => {
const minus = this.showToday > 0 ? 0 : 24 * 60 * 60 * 1000
if (!this.startDate) {
return date && date.valueOf() >= new Date() - minus
}
// 周选择器只能选一季度
const one = 90 * 24 * 3600 * 1000
const minTime = this.startDate - one
const maxTime = this.startDate + one
// 前后只能选七天的倍数
let isTrue = false
// 判断结束时间是否是在一周七天内
const dateTime = new Date(date)
dateTime.setHours(0, 0, 0, 0)
if (dateTime - this.startDate < 0) {
// 前六天
const prev6Date = new Date(this.startDate - 6 * 24 * 60 * 60 * 1000)
prev6Date.setHours(0, 0, 0, 0)
isTrue = (dateTime - prev6Date) % (7 * 24 * 60 * 60 * 1000) === 0
} else {
// 后六天
const next6Date = new Date(this.startDate + 6 * 24 * 60 * 60 * 1000)
next6Date.setHours(0, 0, 0, 0)
isTrue = (dateTime - next6Date) % (7 * 24 * 60 * 60 * 1000) === 0
}
// 由于上面的规则会使起始时间的前一天变成可选状态, 所以要把前一天去除
const yesterday =
new Date(this.startDate).setHours(0, 0, 0, 0) - minus
return (
(date && date.valueOf() >= new Date() - minus) ||
!isTrue ||
yesterday === dateTime.getTime() ||
date.getTime() < minTime ||
date.getTime() > maxTime
)
},
onPick: obj => {
if (obj.minDate && !obj.maxDate) {
this.startDate = obj.minDate.getTime()
} else if (obj.maxDate) {
this.startDate = null
}
}
}
}
},
computed: {
dateRange: {
get() {
return this.dates
},
set(v) {
this.$emit('update', v)
}
}
}
}
</script>