需求:使用element的DatePicker日期選擇器,需要自定義快捷日期選擇,以便于更好的查看數(shù)據(jù)。(此處的日期選擇器為組件,按需修改)
<template>
<div class="block">
<div :class="{ 'show': !actived }" style="transition: all 500ms;">
<el-date-picker
v-model="value1"
type="daterange"
range-separator="-"
start-placeholder="指標(biāo)開(kāi)始時(shí)間"
end-placeholder="指標(biāo)結(jié)束時(shí)間"
value-format="yyyy-MM-dd"
@change="pick"
:picker-options="pickerOptions"
>
</el-date-picker>
</div>
</div>
</template>
<style scoped>
.block {
width: auto;
height: 40px;
overflow: hidden;
}
.show {
opacity: 1;
margin-top: -100px;
transition: all 500ms;
}
</style>
<script>
export default {
props: ['actived'],
data() {
return {
pickerOptions: {
shortcuts: [{
text: '昨日',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24);
end.setTime(end.getTime() - 3600 * 1000 * 24);
picker.$emit('pick', [start, end]);
}
},{
text: '最近7天',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 6);
picker.$emit('pick', [start, end]);
}
},{
text: '上周',
onClick(picker) {
const end = new Date();
const start = new Date();
const lastWeek = new Date().getDay() //獲取今日周幾
//開(kāi)始時(shí)間(上周一與今天間隔的天數(shù))
start.setTime(start.getTime() - 3600 * 1000 * 24 * (7 + lastWeek - 1)); //減1是因?yàn)橐韵聲r(shí)間戳操作,例如周二,但是時(shí)間戳還在周一后的xx小時(shí)
//結(jié)束時(shí)間(上周末與今天間隔的天數(shù))
end.setTime(end.getTime() - 3600 * 1000 * 24 * lastWeek);
picker.$emit('pick', [start, end]);
}
}, {
text: '本月',
onClick(picker) {
const end = new Date();
const start = new Date()
//方法1
const endDay = new Date().getDate() - 1 //獲取今日幾號(hào),減1是因?yàn)橐韵聲r(shí)間戳操作,例如今日16號(hào),但是時(shí)間戳還在15號(hào)后的xx小時(shí)
start.setTime(start.getTime() - 3600 * 1000 * 24 * endDay);
//方法2
// start.setDate(1) //setDate(1)表示設(shè)置開(kāi)始時(shí)間為本月1號(hào),此辦法同樣可以實(shí)現(xiàn)
picker.$emit('pick', [start, end]);
}
},{
text: '上個(gè)月',
onClick(picker) {
const end = new Date();
const start = new Date();
const year = new Date().getFullYear() //獲取年份
let month = new Date().getMonth() //獲取月份
month = month == 0? 1 : month //特殊處理:如果為1月 則下方取1月的天數(shù)
const feb_days = year %4 ? 29 : 28 //判斷今年是否為閏年,如是則二月天數(shù)為29天,反之為28天
let days = [ 31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] //羅列12個(gè)月的天數(shù)
start.setDate(1 - days[ month - 1 ]) //setDate(1)表表示設(shè)置為本月1號(hào),故 本月1號(hào) - 上月天數(shù) = 上月1號(hào)
end.setDate(1 - 1) //以此得出,本月1號(hào) - 1天 = 上月最后一天
picker.$emit('pick', [start, end]);
}
},]
},
value1: '',
};
},
methods: {
pick() {
if (this.value1) {
let time = new Date(this.value1[1]).getTime();
let nowDate = Date.parse(new Date());
if (time > nowDate) {
this.$message({
message: '結(jié)束時(shí)間不能超過(guò)今天',
type: 'error',
duration: 1500
});
return
}
}else {
this.value1 = [ '', '' ]
}
this.$emit('pick', this.value1);
}
}
};
</script>