element dynamically changes the optional time range of el-date-picker

element dynamically changes the optional time range of el-date-picker

When developing web-side projects, we often encounter data query through various time range filter conditions, and the time selector of our element is the most commonly used. Sometimes due to demand, we need to add an optional interval to the time control. A fixed optional range is okay, but what if it is dynamic? Let me show you my application scenario first.
Application Scenario
The picture above is my application scenario. According to the year on the left, which year is selected, the monthly interval on the right can only select the month within that year, and the previous year cannot be selected. After the year on the left is selected, the one on the right The monthly optional interval changes dynamically, so let’s not talk about the code.

//结构代码块
<el-form-item label="年份">
  <el-date-picker
     v-model="value3"
     type="year"
     size="medium"
     placeholder="选择年"
   ></el-date-picker>
 </el-form-item>
<el-form-item label="选择月度" >
    <el-date-picker
       v-model="value4"
       type="monthrange"
       clearable
       range-separator="至"
       start-placeholder="开始月份"
       end-placeholder="结束月份"
       :picker-options="pickerOptions"  //这个属性是关键
       >
     </el-date-picker>
 </el-form-item>

The logic code below

data(){
    
    
   let disabledDate = (time) => {
    
    //这个关键属性我们一定要写在data的里面并且return的外面,这是动态改变区间的关键
      let year = moment(this.value3).format('YYYY')//根据左边年份的时间获取年
      var firstMonth= new Date(+year,1,1);//element的时间控件区间控制是基于js的时间对象来控制的,我们需要转时间对象
      firstMonth.setMonth(0);//设置为这一年的第一个月,这里的0是下标
      var lastMonth= new Date(+year,1,1);//转时间对象
       lastMonth.setMonth(11);//设置为这一年的最后一个月,这里的11是下标
      return time.getTime() > new Date(lastMonth)  || time.getTime() < new Date(firstMonth) 
      //这一年的第12月份的以后的月份不能选,这一年1月份之前的月份也不能选
    }
    return {
    
    
      value3: moment(new Date()).format("YYYY"),
      pickerOptions: {
    
    
        disabledDate,//上面处理好逻辑扔到这来,和表单自定义校验规则一个套路
      },
  },

The above is all the logic and code. After this operation, I feel that I have to take a good look at some things about the native time object of js. Haha, embarrassing

Guess you like

Origin blog.csdn.net/m0_52313178/article/details/124618071