vue项目elementUI,需求为时间范围搜索,带快捷键并且只能选择今天之前,90天内的时间。搜索今天为实时数据,不能使用时间段,只能单独搜索。
需求是今天不可选,只有时间为空时才查询今天,所有下面代码中时间段快捷选择时,结束时间都是昨天。具体可根据自己需求修改。
<el-date-picker v-model="time" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
size="small" value-format="yyyyMMdd" :picker-options="disableTime" />
data() {
return {
disableTime: {
disabledDate: (time) => {
return time.getTime() > Date.now() - 1000 * 60 * 60 * 24 || time.getTime() < Date.now() - 1000 * 60 * 60 * 24 * 90
}
},
}
},
<script>
export default {
data() {
return {
// 设置禁用范围
disableTime: {
disabledDate: (time) => {
return time.getTime() > Date.now() - 1000 * 60 * 60 * 24 || time.getTime() < Date.now() - 1000 * 60 * 60 * 24 * 90
},
shortcuts: [
{
text: '今天',
onClick(picker) {
picker.$emit('pick', null)
}
},
{
text: '昨天',
onClick(picker) {
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
picker.$emit('pick', [start, start])
}
},
{
text: '最近一周',
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
picker.$emit('pick', [start, end])
}
},
{
text: '最近一个月',
onClick(picker) {
const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
picker.$emit('pick', [start, end])
}
}
]
},
}
}
}
</script>
d2-crud-plus中代码
export const crudOptions = (vm) => {
return {
columns: [
{
title: '时间',
key: 'time',
type: 'datetime',
search: { // 搜索
disabled: false, // 是否禁用该字段的查询
width: '250px',
component: { // 查询框组件配置,默认根据form配置生成
name: 'el-date-picker',
props: {
'value-format': 'yyyy-MM-dd',
type: 'daterange',
'range-separator': '-',
'start-placeholder': '开始时间',
'end-placeholder': '结束时间',
'picker-options': {
disabledDate(time) {
return time.getTime() > Date.now() - 1000 * 60 * 60 * 24 || time.getTime() < Date.now() - 1000 * 60 * 60 * 24 * 90
},
shortcuts: shortcuts
}
}
},
order: 2 // 查询字段排序,数字越小越靠前
}
},
]
}
}
const shortcuts = [
{
text: '今天',
onClick(picker) {
picker.$emit('pick', null)
}
}, {
text: '昨天',
onClick(picker) {
const start = toNooning()
const end = toNooning()
addDays(start, -1)
addDays(end, -1)
picker.$emit('pick', [start, end])
}
}, {
text: '近一周',
onClick(picker) {
const start = toNooning()
const end = toNooning()
addDays(start, -7)
addDays(end, -1)
picker.$emit('pick', [start, end])
}
}, {
text: '近一月',
onClick(picker) {
const start = toNooning()
const end = toNooning()
addDays(start, -30)
addDays(end, -1)
picker.$emit('pick', [start, end])
}
}
]
function toNooning(date) {
if (date == null) {
date = new Date()
}
date.setHours(12)
date.setMinutes(0)
date.setSeconds(0)
return date
}
function addDays(date, days) {
date.setTime(date.getTime() + 3600 * 1000 * 24 * days)
}