template代码
<el-date-picker
value-format="yyyy-MM-dd"
v-model="search.date"
type="daterange"
align="right"
placeholder="选择日期范围"
:default-value="this.search.date"
:picker-options="pickerOptions"
range-separator=" ~ ">
</el-date-picker>
顺遍po一个data里面的相关代码,下面的是看你日期选择器的需求哦~
search: {
date:[],
beginDate: '',
endDate: ''
},
pickerOptions: {
shortcuts: [{
text: '今天',
onClick(picker) {
const end = new Date();
end.setHours(23, 59, 59);
const start = new Date(end);
start.setTime(end.getTime() - 3600 * 1000 * 24 + 1000);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
end.setHours(23, 59, 59);
start.setTime(end.getTime() - 3600 * 1000 * 24 * 7 + 1000);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一个月',
onClick(picker) {
const end = new Date();
const start = new Date();
end.setHours(23, 59, 59);
start.setTime(end.getTime() - 3600 * 1000 * 24 * 30 + 1000);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近三个月',
onClick(picker) {
const end = new Date();
const start = new Date();
end.setHours(23, 59, 59);
start.setTime(end.getTime() - 3600 * 1000 * 24 * 90 + 1000);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一年',
onClick(picker) {
const end = new Date();
const start = new Date();
end.setHours(23, 59, 59);
start.setTime(end.getTime() - 3600 * 1000 * 24 * 365 + 1000);
picker.$emit('pick', [start, end]);
}
}]
},
重点来了 设置时间的区间选择器主要是要在 :default-value=""里面去设置一个数组
我这里的数据就是this.search.date,先设置一个空数组,然后在created里面把日期push 进去
created () {
this.search.beginDate = this.handleTimeOld(new Date()) //2012-12-1 handleTimeOld是我用来获取当月的第一天的
this.search.endDate = this.handleTimeNew(new Date()) //2012-12-1 handleTimeNew是获取今天的日期
this.search.date.push(this.search.beginDate)
this.search.date.push(this.search.endDate)
this.fetchData()
}
上面的就可以了~~~~~能够设置默认值了
下面的是获取日期的方法
handleTimeOld (time, split) { //是我用来获取当月的第一天的
let date = new Date(time)
let year = date.getFullYear()
let month = date.getMonth() + 1
split = '-'
return [year, month, 1].map(num => this.formatNumber(num)).join(split)
},
handleTimeNew (time) { //handleTimeNew是获取今天的日期
let date = new Date(time)
let year = date.getFullYear()
let month = (date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))
let day = date.getDate() > 10 ? date.getDate() : ('0' + date.getDate())
return `${year}-${month}-${day}`
}
下面加上数据格式化
formatNumber(number) {
return String(number)[1] ? String(number) : `0${number}`
},