日期选择器在实际使用中,可能会要求默认固定日期、回显日期或者是时间固定点(00:00:00到23:59:59)
<template>
<div>
<el-date-picker
@change="handleChange"
v-model="dateValue"
type="daterange"
align="right"
unlink-panels
:clearable=false
value-format="timestamp"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
:picker-options="pickerOptions"
:default-time="['00:00:00', '23:59:59']">
el-date-picker>
div>
template>
<script>
export default {
name: 'DateRangePicker',
props: {
defaultTimeRange: {
type: Object,
default() {
return {};
}
}
},
data() {
return {
dateValue: '',
pickerOptions: {
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
const start = new Date(new Date().toLocaleDateString()); ;
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
},
{
text: '最近一个月',
onClick(picker) {
const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
const start = new Date(new Date().toLocaleDateString()); ;
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
},
{
text: '最近三个月',
onClick(picker) {
const end = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1);
const start = new Date(new Date().toLocaleDateString()); ;
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
}
};
},
mounted() {
this.dateValue = [new Date(this.defaultTimeRange.from), new Date(this.defaultTimeRange.to)];
},
methods: {
handleChange(time) {
time = time || [];
this.$emit('handleChange', {start_time: time[0], end_time: time[1]});
}
}
};
script>
父组件index.vue
<DateRangePicker @handleChange="handleTime" :default-time-range="defaultTimeRange"/>
<script>
import { generateTodayDefaultTimeRange } from '@/utils/utils';
export default {
data () {
return {
defaultTimeRange: { ...generateTodayDefaultTimeRange() }
}
}
methods:{
handleTime(time) {
//console.log(time)获取选择时间
}
}
}
</script>
引用JSutils.js
// 今日默认时间范围
export function generateTodayDefaultTimeRange(date = new Date()) {
const to = formatDateTime(new Date(date.getTime()));
const from = formatDateTime(new Date(date.getTime()));
return { from, to };
}
default-time
设置时间点固定为起始的00:00:00到23:59:59
value-format="timestamp"