项目中多处使用到了时间范围选择器组件,并且有的需要默认选中当前日期-往前一个月?或者?展示最近7天等,所以最好是将其封装,通过props传递数据即可
// html
<template>
<div class="disflex">
<label style="margin-right:10px;">{{ datename }}</label>
<el-date-picker
v-model="dateRange"
type="daterange"
value-format="yyyy-MM-dd"
clearable
size="mini"
@blur="getDate"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期">
</el-date-picker>
</div>
</template>
// js
<script>
export default {
props: ["dateName", "isNeedInitDate"]
data() {
return {
dateRange: []
};
},
create() {
// 这里是控制初始化的时候是否需要显示默认时间
if (this.isNeedInitDate == 'true') {
this.getInitDate()
}
this.$emit("getDate", this.dateRange)
},
methods: {
//默认展示当前日期-往前推一个月
getInitDate() {
//当前时间
let nowdate = new Date()
let year = nowdate.getFullYear().toString()
let month = nowdate.getMonth()+1 < 10 ? "0" + (nowdate.getMonth()+1).toString() : (nowdate.getMonth()+1).toString()
let day = nowdate.getDate()+1 < 10 ? "0" + (nowdate.getDate()+1).toString() : (nowdate.getDate()+1).toString()
let nowdate = year + "-" + month + "-" + day
//当天往前推一个月时间
nowdate.setMonth(nowdate.getMonth()-1)
let y = nowdate.getFullYear().toString()
let m = nowdate.getMonth()+1 < 10 ? "0" + (nowdate.getMonth()+1).toString() : (nowdate.getMonth()+1).toString()
let d = nowdate.getDate()+1 < 10 ? "0" + (nowdate.getDate()+1).toString() : (nowdate.getDate()+1).toString()
let lastdate = y + "-" + m + "-" + d
this.dateRange = [lastdate, nowdate]
},
getDate() {
this.$emit('getDate', this.dateRange)
},
clearDate() {
this.dateRange = []
},
//默认展示月第一天-当天
getInitDate() {
//当前时间
let date= new Date()
let year = date.getFullYear().toString()
let month = date.getMonth()+1 < 10 ? "0" + (nowdate.getMonth()+1).toString() : (nowdate.getMonth()+1).toString()
let day = date.getDate()+1 < 10 ? "0" + (nowdate.getDate()+1).toString() : (nowdate.getDate()+1).toString()
//当月第一天
let start = year + "-" + month + "-01"
//当天
let end = year + "-" + month + "-" + day
this.dateRange = [start, end]
},
}
};
</script>
// 父组件引入:
<datePicker ref="datePicker" @getDate="getDate" isNeedInitDate="false">
getDate(val) {
this.dateRange = val
}