Element UI Time picker encapsulation Secondary encapsulation is easy to use and convenient to support separate pass in the start time and end time default date can be added to the minutes and seconds
Create the DateRange folder index.vue component file in the global Components
- The following code
<template>
<div>
<el-date-picker
v-model="dateRange"
type="daterange"
range-separator="To"
start-placeholder="Start Date"
end-placeholder="End Date"
value-format="yyyy-MM-dd"
unlink-panels
:clearable="clearable"
@change="changeDate"
/>
</div>
</template>
<script>
export default {
name: 'DateRangeSelect'.props: {
form: { // Save data from the request object such as listQuery{startTime: ",endTime: "}
required: true.type: Object
},
startDateKey: { // Start time
required: true.type: String.default: 'startDate'
},
endDateKey: {// End time
required: true.type: String.default: 'endDate'
},
startDateVal: {
type: String.default: ' '
},
endDateVal: {
type: String.default: ' '
},
clearable: {// Whether it can be cleared
type: Boolean.default: true
},
canSameDate: {// Whether to allow the same start and end time
type: Boolean.default: true
},
resultDateFormat: { // The format of the request is start time + 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('Start date and end date cannot be the same, please re-select')
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] = `The ${this.dateRange[0]}00:00:00 `
this.form[this.endDateKey] = `The ${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>
Copy the code
use
1. Use it where necessary
import DateRange from '@/components/DateRange'
components: {
DateRange
},
data(){
return{
listQuery: {
startTime: null.endTime: null,}}}Copy the code
2. The page
<el-form-item label="Date.">
<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>
Copy the code