elementui中el-date-picker的type=monthrange时根据开始结束判断可选范围不能大于12个月
时间: 2023-12-06 08:45:36 浏览: 31
可以通过自定义可选日期范围的函数来实现这个功能。具体实现步骤如下:
1. 在el-date-picker组件中设置type为'monthrange',并且设置一个自定义的可选日期范围函数rangeMethod。
```
<el-date-picker
v-model="dateRange"
type="monthrange"
:range-separator="separator"
:picker-options="pickerOptions"
:range-method="rangeMethod">
</el-date-picker>
```
2. 在data中定义一个变量maxRangeMonth,表示可选日期范围的最大月份跨度
```
data() {
return {
dateRange: [],
separator: ' - ',
pickerOptions: {
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}]
},
maxRangeMonth: 12
}
}
```
3. 实现自定义的可选日期范围函数rangeMethod,根据开始和结束日期计算它们之间的月份跨度,如果超过了maxRangeMonth,则不可选。具体代码如下:
```
methods: {
rangeMethod: function (val) {
const startMonth = val[0].getMonth();
const endMonth = val[1].getMonth();
const monthDiff = (endMonth - startMonth) + 1;
if (monthDiff > this.maxRangeMonth) {
return false;
}
return true;
}
}
```
这样就可以实现根据开始和结束判断可选范围不能大于12个月的功能了。