DatePicker 日期选择器的使用(当日、近一周、近一月...)
template部分
<el-form-item label="操作日期:" style="margin-left: 50px;"><el-date-pickerv-model="dateRange"type="datetimerange"range-separator="~"start-placeholder="开始日期"end-placeholder="结束日期":shortcuts="shortcuts":disabled-date="disabledDate"style="width: 350px;":default-time="defaultTime"/>
</el-form-item>
script部分
// 初始化
const dateRange = ref<[Date, Date] | null>(null)// 禁用当前日期之后的时间
const disabledDate = (time: Date) => {return time.getTime() > Date.now()
}const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0),new Date(2000, 2, 1, 23, 59, 59)
]const shortcuts = [{text: '当日',value: () => {const end = new Date()const start = new Date(end)start.setHours(0, 0, 0, 0) // 设置为当天的凌晨 00:00:00return [start, end]}},{text: '近1周',value: () => {const end = new Date()const start = new Date()start.setDate(start.getDate() - 7)return [start, end]}},{text: '近1月',value: () => {const end = new Date()const start = new Date()start.setMonth(start.getMonth() - 1)return [start, end]}},{text: '近3个月',value: () => {const end = new Date()const start = new Date()start.setMonth(start.getMonth() - 3)return [start, end]}},{text: '近6个月',value: () => {const end = new Date()const start = new Date()start.setMonth(start.getMonth() - 6)return [start, end]}}
]const quickSetDateRange = (range: string) => {const now = new Date()let start: Dateswitch (range) {case 'day':start = new Date(now)breakcase 'week':start = new Date(now)start.setDate(now.getDate() - 7)breakcase 'month':start = new Date(now)start.setMonth(now.getMonth() - 1)breakcase '3months':start = new Date(now)start.setMonth(now.getMonth() - 3)breakcase '6months':start = new Date(now)start.setMonth(now.getMonth() - 6)breakdefault:start = new Date(now)}dateRange.value = [start, now]
}// 初始化时过滤数据并设置默认日期范围为近一周
quickSetDateRange('week')
quickDateRange.value = 'week'
UI效果