element-UI封装某一具体日期和时间范围选择器
背景
项目开发遇到了需要选择某一个日期的某一个时间段,例如:上门取件时间之类的,某一时间段,所以封装一个时间选择组件。
代码实现参考原文章:blog.csdn.net/weixin_4349…
基本实现方式一致,增加一点选择的体验bug优化。
效果
代码实现
<template>
<div class="oneDayTimeSelect-container">
<div
class="inputRectangle"
@click.stop="openDatePicker"
@mouseover="isShow = true"
@mouseout="isShow = false"
>
<span class="">{{ assignForm.time }}</span>
<i
v-if="assignForm.time && isShow"
class="dataIcon el-icon-circle-close"
@click.stop="clearTimeFuc()"
></i>
<i v-else class="el-icon-date dataIcon"></i>
<!-- 日期 -->
<el-date-picker
ref="dateRef"
v-model="dayTime"
class="pickerDate"
type="date"
format="yyyy-MM-dd"
value-format="yyyy-MM-dd"
@change="showTimeRange"
/>
<!-- 时间范围 -->
<el-time-picker
ref="timeRangeRef"
v-model="timeInterval"
:readonly="timeDisabled"
class="pickerTime"
is-range
value-format="HH:mm"
format="HH:mm"
@change="changeTime"
/>
</div>
</div>
</template>
<script>
export default {
props: {
form: {
type: Object,
default: () => {
return {}
}
},
startProp: {
type: String,
default: 'startTime'
},
endProp: {
type: String,
default: 'endTime'
}
},
data () {
return {
isShow: false,
// data
assignForm: {
time: '' // 默认时间
},
dayTime: '', // 日期
canSelectTime: false,
timeInterval: '' // 时间区间
}
},
computed: {
timeDisabled () {
return !(this.dayTime && this.canSelectTime)
}
},
watch: {
dayTime (val) {
if (val) {
this.form[this.startProp] = this.timeInterval[0]
? this.dayTime + ' ' + this.timeInterval[0]
: this.dayTime + ' 00:00'
this.form[this.endProp] = this.timeInterval[1]
? this.dayTime + ' ' + this.timeInterval[1]
: this.dayTime + ' 23:59'
} else {
this.form[this.startProp] = ''
this.form[this.endProp] = ''
}
},
timeInterval (val) {
if (val) {
this.form[this.startProp] = this.dayTime + ' ' + val[0]
this.form[this.endProp] = this.dayTime + ' ' + val[1]
} else {
this.form[this.startProp] = ''
this.form[this.endProp] = ''
}
}
},
methods: {
// 打开日期option
openDatePicker () {
this.clearTimeFuc()
// 显示日期选择器
this.$refs.dateRef.focus() // 手动开启时间弹窗
},
// 打开时间区间option
showTimeRange (val) {
this.assignForm.time = `${val} 00:00 - 23:59`
this.canSelectTime = true
this.$nextTick(() => {
this.$refs.timeRangeRef.focus()
})
},
changeTime (val) {
this.canSelectTime = false
this.assignForm.time = `${this.dayTime} ${val[0]} - ${val[1]}`
},
clearTimeFuc () {
this.assignForm.time = ''
this.dayTime = '' // 日期
this.timeInterval = '' // 时间区间
}
}
}
</script>
<style scoped lang="scss">
.inputRectangle {
width: 320px;
min-width: 320px;
height: 36px;
line-height: 36px;
background: #fff;
border-radius: 4px;
border: 1px solid #dcdfe6;
position: relative;
padding: 5px 0 5px 15px;
color: #111;
font-size: 16px;
z-index: 1;
.dataIcon {
position: absolute;
top: 50%;
right: 8px;
width: 16px;
height: 16px;
color: #c0c4cc;
transform: translateY(-50%);
}
}
.pickerDate {
opacity: 0;
position: absolute;
left: 0;
bottom: 2px;
z-index: -1;
}
.pickerTime {
opacity: 0;
position: absolute;
left: 224px;
bottom: 2px;
width: 0px;
height: 0px;
z-index: -1;
}
</style>