elementui 时间选择器 快捷前12个月选择
<template>
<el-date-picker
v-model="alarmDate"
type="daterange"
unlink-panels
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
:picker-options="pickerOptions2"
value-format="yyyyMMdd"
style="margin-right: 10px; width: 400px">
</el-date-picker>
</template>
data:
alarmDate: [],
pickerOptions2: {
disabledDate(time) {
return time.getTime() > Date.now()
},
shortcuts: []
}
created:
// validate.js
// eslint-disable-next-line no-extend-native
Date.prototype.format = this.validate.format
const date = new Date().format('yyyyMMdd')
this.alarmDate = [date, date]
this.getTimeObj()
methods:
mGetDate(year, month) {
var d = new Date(year, month, 0)
return d.getDate()
},
getTimeObj() {
var dataArr = []
var data = new Date()
data.setMonth(data.getMonth() + 1, 1) // 获取到当前月份,设置月份
for (var i = 0; i < 12; i++) {
data.setMonth(data.getMonth() - 1) // 每次循环一次 月份值减1
var m = data.getMonth() + 1
m = m < 10 ? '0' + m : m
dataArr.push(data.getFullYear() + '-' + (m))
}
const endDate = []
for (let i = 1; i < dataArr.length; i++) {
const arr = dataArr[i].split('-')
const obj = {}
let endDay = ''
if (arr[1][0] === '0') {
endDay = this.mGetDate(parseInt(arr[0]), parseInt(arr[1][1]))
obj.text = arr[0] + '年' + arr[1][1] + '月'
} else {
endDay = this.mGetDate(parseInt(arr[0]), parseInt(arr[1]))
obj.text = arr[0] + '年' + arr[1] + '月'
}
obj.start = arr[0] + arr[1] + '01'
obj.end = arr[0] + arr[1] + endDay
endDate.push(obj)
}
console.log('end', endDate)
const arrTime = [
{
text: '本月',
onClick(picker) {
const end = new Date()
const start = new Date()
start.setDate(1)
picker.$emit('pick', [start, end])
}
}
]
for (let i = 0; i < endDate.length; i++) {
const item = {
text: endDate[i].text,
onClick(picker) {
picker.$emit('pick', [endDate[i].start, endDate[i].end])
}
}
arrTime.push(item)
}
this.pickerOptions2.shortcuts = arrTime
}