需求: 默认选择近一个月,根据DefaultTimeRange字段获取默认查询时长,最多查询日期范围为两年的时间
原版本
html
<el-date-picker
v-model="timeRange"
:range-separator="null"
class="filter-item search-item date-range-item"
end-placeholder="结束日期"
format="yyyy-MM-dd"
start-placeholder="开始日期"
type="daterange"
value-format="yyyy-MM-dd"
:picker-options="pickerOptions"
/>
js
// el-date-picker配置项
pickerOptions: {
disabledDate(time) {
//根据当前日期 --- 禁止选中之后的日期
return time.getTime() > Date.now()
},
onPick(time) {
// 仅允许筛选近两年的数据
this.$nextTick(() => {
// time.minDate -- 选中开始的时间
let start = new Date(time.minDate)
let end = new Date(time.maxDate)
// console.log(start, end , end - start);
if (end - start > 3600 * 1000 * 24 * 2 * 365) {
that.$message.info("仅允许筛选近两年的数据")
start = new Date()
end = new Date().valueOf() - 3600 * 1000 * 24 * 365 * 2
that.timeRange[0] = new Date(end)
.toLocaleDateString()
.replaceAll("/", "-")
that.timeRange[1] = start
.toLocaleDateString()
.replaceAll("/", "-")
that.fetchTable()
that.fetchScrapCount()
}
})
// 关闭--时间控件下拉框
}
},
// 查询表格
fetchTable(params = {}) {
this.loading = true
if (this.timeRange && this.timeRange.length) {
this.queryParams.model.startTime = this.timeRange[0]
this.queryParams.model.endTime = this.timeRange[1]
} else {
this.queryParams.model.startTime = ""
this.queryParams.model.endTime = ""
}
...请求
},
bug
1.可直接输入超过2年范围的时间
2.时间限制不严谨,应该按月来计算
修改后代码
利用momentjs和整理需求 二次封装element-ui的date-picker组件
html
<!-- 日期范围选择 -->
<HCDatePickRange
ref="HCDataPickRangeDom"
@datePickCallBack="datePickCallBack"
/>
js
/**
* datepick组件传递CallBack
* @param {Array} timeRange - 时间范围
* @param {Boolean} isNeed - 是否需要直接重新获取数据
*/
datePickCallBack(timeRange, isNeedLoad = false) {
this.timeRange = timeRange
if(isNeedLoad) {
this.getAllData()
}
},
// 组件内容
// 初始化timeRange
initParams() {
return [
moment()
.subtract(this.DefaultTimeRange, "months")
.format("YYYY-MM-DD"),
moment().format("YYYY-MM-DD")
]
},
// 获取默认时间范围
async getDefaultTimeRange() {
await Setting.getValue({ key: "DefaultTimeRange" }).then(res => {
if (res.status == 200) {
this.DefaultTimeRange = Number(res.data.data)
this.timeRange = this.initParams()
this.$emit("datePickCallBack", this.timeRange, true)
}
})
},
// 用户确认选定的值时触发
pickerChange() {
let min = moment(this.timeRange[0])
let max = moment(this.timeRange[1])
this.timeRequire(min, max)
},
// 日期选择校验
timeRequire(min, max) {
// console.log(min, max, 91)
if (max && min && max.diff(min, "years", true) > 2) {
this.$message.info("筛选时间跨度不能超过两年")
let newRange = []
newRange[0] = moment()
.subtract(2, "years")
.format("YYYY-MM-DD")
newRange[1] = moment().format("YYYY-MM-DD")
// 重新赋值让日期控件回显筛选条件
this.timeRange.splice(0, 2)
this.timeRange.push(...newRange)
// 选择超出2年
this.$emit("datePickCallBack", newRange, true)
} else {
this.$emit("datePickCallBack", this.timeRange, false)
}
},
// 重新赋值让日期控件回显筛选条件
resetTimeRange() {
this.timeRange.splice(0, 2)
this.timeRange.push(...this.initParams())
}