element ui 时间选择器封装二次封装简单好用方便支持分开传入开始时间和结束时间 默认日期可以加上时分秒
在全局components中创建DateRange文件夹index.vue组件文件
- 代码如下
<template>
<div>
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
value-format="yyyy-MM-dd"
unlink-panels
:clearable="clearable"
@change="changeDate"
/>
</div>
</template>
<script>
export default {
name: 'DateRangeSelect',
props: {
form: { //保存请求对象中的数据 如:listQuery{startTime:'',endTime:''}
required: true,
type: Object
},
startDateKey: { //开始时间
required: true,
type: String,
default: 'startDate'
},
endDateKey: {//结束时间
required: true,
type: String,
default: 'endDate'
},
startDateVal: {
type: String,
default: ''
},
endDateVal: {
type: String,
default: ''
},
clearable: {//是否可以清除
type: Boolean,
default: true
},
canSameDate: {//是否允许开始结束时间一致
type: Boolean,
default: true
},
resultDateFormat: { //请求的格式是否是开始时间加 00:00:00 结束加23:59:59
type: String,
default: 'yyyy-MM-dd',
validator(val) {
return ['yyyy-MM-dd', 'yyyy-MM-dd HH:mm:ss'].indexOf(val) !== -1
}
}
},
computed: {},
data() {
return {
dateRange: []
}
},
created() {
this.dateRange = this.initDate()
},
methods: {
initDate() {
if (this.startDateVal && this.endDateVal) {
return [this.startDateVal, this.endDateVal]
}
return []
},
changeDate(arr) {
if (!this.canSameDate) {
if (Array.isArray(arr) && arr.length && arr[0] === arr[1]) {
this.$message.error('开始日期和结束日期不能相同,请重新选择')
setTimeout(() => {
this.dateRange = []
}, 200)
}
}
},
getDate() {
if (Array.isArray(this.dateRange) && this.dateRange.length) {
if (this.resultDateFormat === 'yyyy-MM-dd HH:mm:ss') {
this.form[this.startDateKey] = `${this.dateRange[0]} 00:00:00`
this.form[this.endDateKey] = `${this.dateRange[1]} 23:59:59`
} else {
this.form[this.startDateKey] = this.dateRange[0]
this.form[this.endDateKey] = this.dateRange[1]
}
} else {
this.resetDate()
}
},
resetDate() {
this.form[this.startDateKey] = null
this.form[this.endDateKey] = null
this.dateRange = []
}
}
}
</script>
使用
1.需要使用的地方引入
import DateRange from '@/components/DateRange'
components: {
DateRange
},
data(){
return{
listQuery: {
startTime: null,
endTime: null,
},
}
}
2.页面中
<el-form-item label="日期:">
<date-range
ref="DateRangeSelect"
:form="listQuery"
start-date-key="startTime"
end-date-key="endTime"
result-date-format="yyyy-MM-dd HH:mm:ss"
/>
</el-form-item>