<template>
<el-date-picker
v-model="timeData"
type="daterange"
start-placeholder="开始日期"
end-placeholder="结束日期"
:picker-options="pickerOption"
value-format="yyyy-MM-dd"
@change="handleChangeDate"
></el-date-picker>
</template>
<script>
import { resetData } from '@/utils'
export default {
name: 'DaterangePicker',
props: {
month: {
required: false,
type: Number,
default: 6
},
value: {
required: false,
default: () => { return [] },
type: Array
}
},
data: () => {
return {
timeData: [],
startTime: '',
pickerOption: {}
}
},
watch: {
value(val) {
this.timeData = val
this.resetOption()
this.initPickerOption()
}
},
created() {
this.initPickerOption()
this.timeData = this.value
},
methods: {
initPickerOption() {
this.pickerOption = {
onPick: (time) => {
this.startTime = time.minDate
this.setDisabledDate()
}
}
},
setDisabledDate() {
const fnc = (time) => {
let currentTime = ''
if (this.startTime) {
currentTime = this.startTime
const threeMonths = currentTime.setMonth(currentTime.getMonth() + this.month)
currentTime.setMonth(currentTime.getMonth() - this.month)
const lastMonths = currentTime.setMonth(currentTime.getMonth() - this.month)
currentTime.setMonth(currentTime.getMonth() + this.month)
return time.getTime() < lastMonths || time.getTime() > threeMonths
}
}
this.$set(this.pickerOption, 'disabledDate', fnc)
},
resetOption() {
resetData(this, 'pickerOption')
},
handleChangeDate(val) {
this.timeData = val
val || (this.startTime = '')
this.resetOption()
this.$emit('input', this.timeData)
this.$emit('change', this.timeData)
}
}
}
</script>
<style scoped lang="scss">
.el-date-editor{
padding: 3px;
}
</style>
举例:当前选择是2022年1.1,那么往前最多可以选择到2021.7.1,往后则最多可以选择到2022.7.1.非常实用。
以上是封装好的,项目中直接引用,
<daterange-picker :value="rangeTime" :month="6" @change="handleChangeDate"></daterange-picker>
data(){
return:{
rangeTime:[]
}
},
methods:{
handleChangeDate(val) {
if (val) {
this.searchParams.startTime = val[0]
this.searchParams.endTime = val[1]
} else {
this.searchParams.startTime = ''
this.searchParams.endTime = ''
}
},
}