el-time-picker对于开始时间受结束时间限制的处理

el-time-picker中要使用时间范围的选择,需要添加is-range属性,添加之后,开始时间大于结束时间的选项是不能被选择的,目前的第一种解决方案使用了原生标签加上el自带的样式解决。

// 通常使用如下
<el-time-picker v-if="scope.row.configType == '8' || scope.row.configType == '9'"  
is-range v-model="scope.row.val" range-separator="-" 
:format="'HH:mm'" :value-format="'HH:mm'" 
start-placeholder="开始时间" end-placeholder="结束时间" 
:picker-options="{selectableRange: '08:00-08:00'}"
@change="()=>{handleValueChange(scope.row)}">
</el-time-picker>

// 使用原生标签input,并添加验证
<div v-if="scope.row.configType == '8' || scope.row.configType == '9'" 
class="el-date-editor el-range-editor el-input__inner el-date-editor--timerange el-range-editor--medium">
<i class="el-input__icon el-range__icon el-icon-time"></i>
<input autocomplete="off" placeholder="开始时间" v-model="scope.row.beginTime" class="el-range-input" @change="()=>{handleValueChange(scope.row)}">
<span class="el-range-separator">-</span>
<input autocomplete="off" placeholder="结束时间" v-model="scope.row.endTime" class="el-range-input" @change="()=>{handleValueChange(scope.row)}">
<i class="el-input__icon el-range__close-icon"></i>
</div>

// 验证的表达式 [01]?[0-9]表示的是00-19 2[0-3]表示的是20-23 [0-5][0-9]表示的是00-59
const regex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/

// 在el中可以使用扩展指令的方式来限制输入的格式
Vue.directive('time-format', {
  bind: function (el, binding, vnode) {
    el.oninput = function (e) {
      if (!e.isTrusted) return
 
      // 正则表达式,匹配08:00格式的时间
      const regex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
 
      // 如果输入的值不匹配格式,则将其设置回上一个合法的值
      if (!regex.test(e.target.value)) {
        vnode.elm.value = binding.value
      }
    }
  }
})