el-date-picker 限制选择范围最大为一年:
主要代码为::picker-options="pickerOptions" 以及 @blur="pickerBlur"
<el-date-pickerv-model="transactionTime"type="daterange"style="width: 200px"size="small"format="yyyy-MM-dd"value-format="yyyy-MM-dd"start-placeholder="开始时间"end-placeholder="结束时间":picker-options="pickerOptions"clearable@blur="pickerBlur"/>
设置快捷选项,设置禁用选项方法:
data() {return {transactionTime: null,pickDate: '', // 存放getPickDate获取的数据pickerOptions: {onPick: this.getPickDate,disabledDate: this.disabledDate,shortcuts: [{text: '今天',onClick(picker) {picker.$emit('pick', [new Date(), new Date()])}},{text: '最近一周',onClick(picker) {const end = new Date();const start = new Date();start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);picker.$emit('pick', [start, end])}},{text: '最近一个月',onClick(picker) {const end = new Date();const start = new Date();start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);picker.$emit('pick', [start, end])}},{text: '最近三个月',onClick(picker) {const end = new Date();const start = new Date();start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);picker.$emit('pick', [start, end]);}}]},};},
设置禁用选项的方法(限制选择范围最大为一年):
methods: {getPickDate(pick) {this.pickDate = pick},disabledDate(date) {const { minDate, maxDate } = this.pickDateif (minDate && !maxDate) {const diff = Math.abs(minDate.valueOf() - date.valueOf())// 日期选择范围不能大于一年if (diff > 1000 * 3600 * 24 * 365) {return true}}},pickerBlur(val) {this.pickDate = '' // 清空getPickDate获取的数据},}
设置 transactionTime 最开始的默认时间为三个月:
created() {const end = new Date()const start = new Date()start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)this.transactionTime = [this.parseTime(start, '{y}-{m}-{d}'), this.parseTime(end, '{y}-{m}-{d}')]},
其中parseTime方法为:
// 日期格式化
export function parseTime(time, pattern) {if (arguments.length === 0 || !time) {return null}const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'let dateif (typeof time === 'object') {date = time} else {if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {time = parseInt(time)} else if (typeof time === 'string') {time = time.replace(new RegExp(/-/gm), '/');}if ((typeof time === 'number') && (time.toString().length === 10)) {time = time * 1000}date = new Date(time)}const formatObj = {y: date.getFullYear(),m: date.getMonth() + 1,d: date.getDate(),h: date.getHours(),i: date.getMinutes(),s: date.getSeconds(),a: date.getDay()}const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {let value = formatObj[key]// Note: getDay() returns 0 on Sundayif (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }if (result.length > 0 && value < 10) {value = '0' + value}return value || 0})return time_str
}
如果重置搜索条件时需要重置回默认时间,记得重置方法内也要写入默认时间:
/** 重置按钮操作 */resetQuery() {this.queryParams = this.$options.data().queryParamsconst end = new Date()const start = new Date()start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)this.queryParams.transactionTime = [this.parseTime(start, '{y}-{m}-{d}'), this.parseTime(end, '{y}-{m}-{d}')]this.handleQuery()},