我们在平常的开发中经常会用到日期范围的插件,根据日期范围查询相应的各种数据,但是这时候后端接口需要的是开始时间和结束时间两个字段,但是element ui 的日期范围插件他返回的是一个数组,我们就需要把数组拆分成两个字段,每次都要拆分,有点浪费工作量,那我们不如直接提取一个公共的插件,二次封装一下,每次传入两个值,对应开始和结束时间,具体方法如下:
html部分:
<template>
<div ref='datetimerange'>
<el-date-picker
v-model="datetime"
:disabled="disabled"
:clearable="clearable"
:type="type"
:size="size"
:start-placeholder="startText"
:end-placeholder="endText"
:format="format"
:unlink-panels="unlinkPanels"
:value-format="valueFormat"
:picker-options="pickerOptions"
:default-time="['00:00:00','23:59:59']"
align="center"
@change="change">
</el-date-picker>
</div>
</template>
JS部分:
export default {
name: 'dateTimeRange',
props: {
unlinkPanels: {
type: Boolean,
default: true
},
clearable: {
type: Boolean,
default: true
},
shortcutsType: {
type: String,
default: 'nearly'
},
startTime: {
type: String,
default: ''
},
type: {
type: String,
default: 'daterange'
},
endTime: {
type: String,
default: ''
},
valueFormat: {
type: String,
default: 'yyyy-MM-dd'
},
format: {
type: String,
default: 'yyyy-MM-dd'
},
size: {
type: String,
default: ''
},
disabled: {
type: Boolean,
default: false
}
},
data() {
return {
datetime: [],
defaultStartTime: '',
defaultEndTime: ''
}
},
computed: {
endText() {
return '结束时间'
},
startText() {
return '开始时间'
}
},
watch: {
startTime(newVal, oldVal) {
if (newVal) {
this.datetime = [newVal, this.endTime]
} else {
this.datetime = ''
}
},
endTime(newVal, oldVal) {
if (newVal) {
this.datetime = [this.startTime, newVal]
} else {
this.datetime = ''
}
},
datetime(newVal, oldVal) {
if (newVal) {
this.updateStartTime(newVal[0])
this.updateEndTime(newVal[1])
} else {
this.updateStartTime('')
this.updateEndTime('')
}
}
},
mounted() {
if (this.startTime && this.endTime) { this.datetime = [this.startTime, this.endTime] }
},
methods: {
change (e) {
if (e) {
this.defaultStartTime = e[0]
this.defaultEndTime = e[1]
this.$emit('change', {
startTime: e[0],
endTime: e[1]
})
} else {
this.defaultStartTime = ""
this.defaultEndTime = ""
this.$emit('change', {
startTime: "",
endTime: ""
})
}
},
updateStartTime(time) {
this.$emit('update:startTime', time)
return time
},
updateEndTime(time) {
this.$emit('update:endTime', time)
return time
}
}
}
网友评论