element 日期选择器date-picker 设置默认月份(当年1月到当前月),结束月份大于开始月份,开始月份小于结束月份
1. 初始月份设置
先放效果图
- 月份选择器
<el-date-picker
v-model="checkFieldFormData.fromDate"
:picker-options="pickerOptionsStart"
type="month"
format="yyyy-MM"
value-format="yyyyMM"
placeholder="开始月份"
>
</el-date-picker>
<span class="speator-date">-</span>
<el-date-picker
v-model="checkFieldFormData.toDate"
:picker-options="pickerOptionsEnd"
type="month"
format="yyyy-MM"
value-format="yyyyMM"
placeholder="结束月份"
>
</el-date-picker>
- 在data中定义
checkFieldFormData: {
fromDate: '',
toDate: ''
}
- 获取默认月份
mounted() {
this.skMonthrangeDefault()
},
skMonthrangeDefault() {
var now = new Date()
let month = now.getMonth() + 1
if (month >= 1 && month <= 9) {
month = '0' + month
}
var startDate = now.getFullYear() + '01' // 形式与value-format一致
var endDate = now.getFullYear() + month.toString()
this.$set(this.checkFieldFormData, 'fromDate', startDate)
this.$set(this.checkFieldFormData, 'toDate', endDate)
},
注意:这里用了$set修改data数据,否则切换月份时,视图不更新。
2. 结束月份大于开始月份,开始月份小于结束月份,禁用月份设置
刚开始的时候看网上的文章好多是把pickerOptionsStart禁用选项写在data里,自己尝试做的时候一直是报错的,就把这些放在了computed中。
computed: {
pickerOptionsStart() {
return {
disabledDate: time => {
if (this.checkFieldFormData && this.checkFieldFormData.toDate) {
const resDate = (new Date(time).getFullYear() + '-' + this.pMonth(new Date(time).getMonth() + 1)).replace(/-/g, '')
return resDate > this.checkFieldFormData.toDate
}
}
}
},
pickerOptionsEnd() {
return {
disabledDate: time => {
if (this.checkFieldFormData && this.checkFieldFormData.fromDate) {
const resDate = (new Date(time).getFullYear() + '-' + this.pMonth(new Date(time).getMonth() + 1)).replace(/-/g, '')
return resDate < this.checkFieldFormData.fromDate
}
}
}
}
},
pMonth(s) {
return s < 10 ? '0' + s : s
},