使用 Element+vue實現開始時間結束時間限制

waillyer發表於2020-12-03

效果

在這裡插入圖片描述

<el-form-item label="開始時間">
   <el-date-picker v-model="startDate" type="datetime" placeholder="選擇日期"
                   format="yyyy-MM-dd HH:mm:ss"
                   value-format="timestamp"
                   :editable="false"
                   :picker-options="pickerOptionsStart" @change="changeStart">
   </el-date-picker>
</el-form-item>
<el-form-item label="結束時間">
   <el-date-picker v-model="endDate" type="datetime" placeholder="選擇日期"
                   style="width: 100%;"
                   format="yyyy-MM-dd HH:mm:ss"
                   value-format="timestamp"
                   :clearable="true"
                   :editable="false"
                   :picker-options="pickerOptionsEnd" @change="changeEnd">
   </el-date-picker>

</el-form-item>
pickerOptionsStart: {},
pickerOptionsEnd: {},
startDate: '',
endDate: '',

 changeStart() { // 限制開始時間
        if (this.endDate != '') {
          if (this.endDate <= this.startDate) {
            this.$message.warning('結束時間必須大於開始時間!');
            this.startDate = '';
          }
        }
        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: (time) => {
            if (this.startDate) {
              return time.getTime() < this.startDate;
            }
          },
        });
      },

      changeEnd() { // 限制結束時間
        console.log(this.endDate);
        if (this.startDate != '') {
          if (this.endDate <= this.startDate) {
            this.$message.warning('結束時間必須大於開始時間!');
            this.endDate = '';
          }
        }

        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: (time) => {
            if (this.endDate) {
              return time.getTime() > this.endDate;
            }
          },
        });
      },

相關文章