基于elementUI自定义时间组件

实现如下可以自定义时间选项的时间组件。


image.png
<CustomTimePicker
                    v-model="movie.playTime"
                    :defaultTime="defaultTime"
                    :prevTime="prevTime"
                    :duration="duration"
                    @cacul="getTime(s_index, m_index, movie)"
                  ></CustomTimePicker>
<template>
<!-- 这是个很不成熟的组件,一次性组件,用完即抛 -->
<!-- 这是个很不成熟的组件,一次性组件,用完即抛 -->
<!-- 这是个很不成熟的组件,一次性组件,用完即抛 -->
<div class="custom-timer-picker-container">
  <div @click.stop="showTimeFun()" style="position: relative;">
    <el-input
      placeholder="请选择时间"
      :value="value"
      @mouseenter.native="handleMouseEnter()"
      @mouseleave.native="handleMouseLeave()"
    >
      <i slot="prefix" class="el-input__icon el-icon-time"></i>
      <i slot="suffix"
        class="el-input__icon"
        @click.stop="handleClickIcon()"
        :class="[showClose ? '' + 'el-icon-circle-close' : '']">
      </i>
    </el-input>
  </div>
  <div class="custom-timer-picker" v-clickoutside="handleClose" :style="{ visibility: pickerVisible ? 'visible' : 'hidden' }">
    <transition name="el-zoom-in-top" @after-leave="$emit('dodestroy')">
      <div class="el-time-panel">
        <div class="el-time-panel__content">
          <div class="time-box">
            <!-- 时 -->
            <el-scrollbar
              @mousemove.native="adjustCurrentSpinner('hours')"
              class="el-time-spinner__wrapper"
              wrap-style="max-height: inherit;"
              view-class="el-time-spinner__list"
              noresize
              tag="ul"
              ref="hours">
              <li
                @click.stop="handleClick('hours', { value: item.hour, index: index, disabled: item.disabled })"
                v-for="(item, index) in hourList"
                :key="item.hour"
                class="el-time-spinner__item"
                :class="{ 'active': item.hour === hours, 'disabled': item.disabled }"
              >
                {{ item.hour }}
              </li>
            </el-scrollbar>
            <!-- 分 -->
            <el-scrollbar
              @mousemove.native="adjustCurrentSpinner('minutes')"
              class="el-time-spinner__wrapper"
              wrap-style="max-height: inherit;"
              view-class="el-time-spinner__list"
              noresize
              tag="ul"
              ref="minutes">
              <li
                @click.stop="handleClick('minutes', { value: item.minute, index: index, disabled: item.disabled })"
                v-for="(item, index) in minuteList"
                :key="item.minute"
                class="el-time-spinner__item"
                :class="{ 'active': item.minute === minutes, 'disabled': item.disabled }"
              >
                {{ item.minute }}
              </li>
            </el-scrollbar>
            <!-- 秒 -->
            <el-scrollbar
              @mousemove.native="adjustCurrentSpinner('seconds')"
              class="el-time-spinner__wrapper"
              wrap-style="max-height: inherit;"
              view-class="el-time-spinner__list"
              noresize
              tag="ul"
              ref="seconds">
              <li
                @click.stop="handleClick('seconds', { value: item.second, index: index, disabled: item.disabled })"
                v-for="(item, index) in secondList"
                :key="item.second"
                class="el-time-spinner__item"
                :class="{ 'active': item.second === seconds, 'disabled': item.disabled }"
              >
                {{ item.second }}
              </li>
            </el-scrollbar>
          </div>
        </div>
        <div class="el-time-panel__footer">
          <button
            type="button"
            class="el-time-panel__btn cancel"
            @click.stop="handleCancel">取消</button>
          <button
            type="button"
            class="el-time-panel__btn confirm"
            @click.stop="handleConfirm()">确定</button>
        </div>
      </div>
    </transition>
  </div>
</div>
</template>
<script>
import Clickoutside from 'element-ui/src/utils/clickoutside';
export default {
  props: {
    // defaultTime用于设置当前时间控件的默认时间,点击取消按钮或者选择了 disabled 的时间的场景使用
    defaultTime: {
      type: String,
      default () {
        return ''
      }
    },
    // prevTime表示前一个设置的最大播放时间,配合 duration 用于计算当前时间控件可选的最早时间
    prevTime: {
      type: String,
      default () {
        return ''
      }
    },
    // duration表示前一个设置最大播放时间的影片的播放时长,配合 prevTime 用于计算当前时间控件可选的最早时间
    duration: {
      type: Number,
      default () {
        return 0
      }
    },
    // 当前时间控件的时间
    value: null
  },
  directives: {
    Clickoutside
  },
  data() {
    return {
      pickerVisible: false,
      showClose: false,
      hours: '',
      minutes: '',
      seconds: '',
      limitTime: '06:00:00',
      hourList: [
        {
          hour: '06',
          disabled: false
        },
        {
          hour: '07',
          disabled: false
        },
        {
          hour: '08',
          disabled: false
        },
        {
          hour: '09',
          disabled: false
        },
        {
          hour: '10',
          disabled: false
        },
        {
          hour: '11',
          disabled: false
        },
        {
          hour: '12',
          disabled: false
        },
        {
          hour: '13',
          disabled: false
        },
        {
          hour: '14',
          disabled: false
        },
        {
          hour: '15',
          disabled: false
        },
        {
          hour: '16',
          disabled: false
        },
        {
          hour: '17',
          disabled: false
        },
        {
          hour: '18',
          disabled: false
        },
        {
          hour: '19',
          disabled: false
        },
        {
          hour: '20',
          disabled: false
        },
        {
          hour: '21',
          disabled: false
        },
        {
          hour: '22',
          disabled: false
        },
        {
          hour: '23',
          disabled: false
        }
      ],
      minuteList: [
        {
          minute: '00',
          disabled: false
        },
        {
          minute: '15',
          disabled: false
        },
        {
          minute: '30',
          disabled: false
        },
        {
          minute: '45',
          disabled: false
        },
        {
          minute: '59',
          disabled: false
        }
      ],
      secondList: [
        {
          second: '00',
          disabled: false
        },
        {
          second: '59',
          disabled: false
        }
      ]
    }
  },
  watch: {
    'pickerVisible'(val) {
      if(val) {
        this.init_hours_minutes_seconds()
        this.$nextTick(()=>{ //这是必要的,不然秒级的59选项选不上
          this.adjustSpinners()
          this.initHourDisableItem()
          this.initMinuteDisableItem()
        })
      }
    },
    'hours'(newVal) {
      if(newVal == '23') {
        if(!this.minuteList.some(item => item.minute == '59')) {
          this.minuteList.push({minute: '59', disabled: false})
        }
      } else {
        if(this.minuteList.some(item => item.minute == '59')) {
          this.minuteList.pop()
          if(this.minutes == '59') {
            this.minutes = this.minuteList[this.minuteList.length - 1].minute
            this.adjustSpinners()
          }
        }
      }
      this.initMinuteDisableItem()
      // 在可选范围区域,则emit
      if(this.checkStatus()) {
        let time = `${this.hours}:${this.minutes}:${this.seconds}`
        this.pickVal(time, true)
      }
    },
    'minutes'(newVal) {
      if(newVal == '59') {
        if(!this.secondList.some(item => item.second == '59')) {
          this.secondList.push({second: '59', disabled: false})
        }
      } else {
        if(this.secondList.some(item => item.second == '59')) {
          this.secondList.pop()
          if(this.seconds == '59') {
            this.seconds = this.secondList[this.secondList.length - 1].second
            this.adjustSpinners()
          }
        }
      }
      this.initHourDisableItem()
      // 在可选范围区域,则emit
      if(this.checkStatus()) {
        let time = `${this.hours}:${this.minutes}:${this.seconds}`
        this.pickVal(time, true)
      }
    },
    'seconds'() {
      // 在可选范围区域,则emit
      if(this.checkStatus()) {
        let time = `${this.hours}:${this.minutes}:${this.seconds}`
        this.pickVal(time, true)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.bindScrollEvent();
    });
  },
  methods: {
    showTimeFun() {
      // 调用 cacul 方法先获取 defaultTime、prevTime、duration
      this.$emit('cacul')
      setTimeout(() => {
        this.pickerVisible = true
      })
    },
    handleClose () {
      this.pickerVisible = false
    },
    handleMouseEnter() {
      if(this.value) {
        this.showClose = true
      }
    },
    handleMouseLeave() {
      this.showClose = false
    },
    handleClickIcon() {
      this.pickVal('', true)
    },
    generateTimeList(delta) {
      let f = n => `${n}`.padStart(2, '0')
      let result = [], date = new Date()
      date.setHours(6)
      date.setMinutes(delta)
      let day = date.getDate()
      while (date.getDate() === day) {
        let h = date.getHours()
        let m = date.getMinutes()
        result.push(`${f(h)}:${f(m)}:00`)
        date.setMinutes(m + delta)
      }
      result = ['06:00:00', ...result, '23:59:59']
      return result
    },
    getLimitTimeToSeconds() {
      let sum = 0
      sum += this.$moment.duration(this.prevTime).as('seconds'); // 上一部电影播放时间转化成秒
      sum += this.duration // 加上上一部电影的播放时长
      if(this.prevTime || this.duration) {
        sum += 8 * 60 // 先加上8分钟(这是最早能选择的时间)
      }
      if(this.prevTime) {
        sum -= 6 * 60 * 60 // 因为从6点开始选择时间,所以减去6个小时的秒数
      }
      return sum
    },
    getLimitTime() {
      let timeToseconds = this.getLimitTimeToSeconds()
      let time = ''
      let timeArr = this.generateTimeList(15)
      for(let i = 0; i < timeArr.length; i++) {
        let totalTime = this.$moment.duration(timeArr[i]).as('seconds') - 6 * 60 * 60 // 需要减去6个小时
        if(totalTime > timeToseconds) { // 找到第一个能选择的时间
          time = timeArr[i]
          break
        }
      }
      return time
    },
    init_hours_minutes_seconds() {
      // 如果当前时间空间选择了时间的话,并且为可选时间,那么初始化为已选择的时间
      // 如果没有选择时间,那么使用上一个时间控件选择的时间加上时长转化过来的时分秒加上8分钟
      // 如果上个控件没有时间,也没有时长,那么使用 06:00:00
      let isBeyond = false
      if(this.prevTime) {
        isBeyond = this.$moment.duration(this.prevTime).as('seconds') + this.duration + 8*60 > this.$moment.duration(this.defaultTime).as('seconds')
      } else if(this.duration) {
        isBeyond = this.duration + 8*60 + 6*60*60 > this.$moment.duration(this.defaultTime).as('seconds')
      }
      if (isBeyond) {
        let time = this.getLimitTime()
        if(time) {
          this.limitTime = time // 这是最早能选择的可选项时间
          let arr = time.split(':')
          this.hours = arr[0]
          this.minutes = arr[1]
          this.seconds = arr[2]
        } else {
          // 找不到时间了 证明已经排满时间了 则全部置灰
          this.hours = '23'
          this.minutes = '59'
          this.seconds = '59'
        }
        return false
      }
      if (this.defaultTime) {
        let arr = this.defaultTime.split(':')
        this.hours = arr[0]
        this.minutes = arr[1]
        this.seconds = arr[2]
        return false
      }
      if (this.value) {
        let arr = this.value.split(':')
        this.hours = arr[0]
        this.minutes = arr[1]
        this.seconds = arr[2]
        return false
      }
      this.hours = '06'
      this.minutes = '00'
      this.seconds = '00'
    },
    bindScrollEvent() {
      const bindFuntion = (type) => {
        this.$refs[type].wrap.onscroll = (e) => {
          this.handleScroll(type, e);
        };
      };
      bindFuntion('hours');
      bindFuntion('minutes');
      bindFuntion('seconds');
    },
    handleScroll(type) {
      let a = this.$refs[type].wrap.scrollTop
      let b = this.scrollBarHeight(type) * 0.5 - 10
      let c = this.typeItemHeight(type)
      let d = type === 'hours' ? this.hourList.length - 1 : type === 'minutes' ? this.minuteList.length - 1 : this.secondList.length - 1
      const index = Math.min(Math.round((a - b / c + 3) / c), d);
      this.modifyDateField(type, index);
    },
    modifyDateField(type, index, value) {
      switch (type) {
        case 'hours': 
          this.hours = this.hourList[index].hour;
          break
        case 'minutes':
          this.minutes = this.minuteList[index].minute;
          break
        case 'seconds':
          this.seconds = this.secondList[index].second;
          break
      }
    },
    checkStatus() {
      let hourArr = this.hourList.filter(item => item.hour == this.hours)
      let minuteArr = this.minuteList.filter(item => item.minute == this.minutes)
      let secondArr = this.secondList.filter(item => item.second == this.seconds)
      return !hourArr[0].disabled && !minuteArr[0].disabled && !secondArr[0].disabled
    },
    scrollBarHeight(type) {
      return this.$refs[type].$el.offsetHeight;
    },
    typeItemHeight(type) {
      return this.$refs[type].$el.querySelector('li').offsetHeight;
    },
    getLiIndex(type, value) {
      let index = 0
      if(type == 'hours') index = this.hourList.findIndex(item => item.hour == value)
      if(type == 'minutes') index = this.minuteList.findIndex(item => item.minute == value)
      if(type == 'seconds') index = this.secondList.findIndex(item => item.second == value)
      return index
    },
    handleClick(type, {value, index, disabled}) {
      if (!disabled) {
        this.modifyDateField(type, index, value);
        this.adjustSpinner(type, value);
      }
    },
    adjustCurrentSpinner(type) {
      this.adjustSpinner(type, this[type]);
    },
    adjustSpinners() {
      this.adjustSpinner('hours', this.hours);
      this.adjustSpinner('minutes', this.minutes);
      this.adjustSpinner('seconds', this.seconds);
    },
    adjustSpinner(type, value) {
      const el = this.$refs[type].wrap;
      if (el) {
        let index = this.getLiIndex(type, value)
        el.scrollTop = Math.max(0, index * this.typeItemHeight(type));
      }
    },
    handleConfirm() {
      if(this.checkStatus()) {
        let time = `${this.hours}:${this.minutes}:${this.seconds}`
        this.pickVal(time, false)
      } else {
        this.pickVal(this.defaultTime, false)
      }
    },
    handleCancel() {
      this.pickVal(this.defaultTime, false)
    },
    pickVal(time, visible) {
      if(!visible) {
        this.pickerVisible = false
      }
      this.$emit('input', time)
    },
    initHourDisableItem() {
      let currentTime = ''
      for(let i = 0; i < this.hourList.length; i++) {
        for(let j = 0; j < this.minuteList.length; j++) {
          if(this.minuteList[j].minute == this.minutes) {
            for(let k = 0; k < this.secondList.length; k++) {
              currentTime = `${this.hourList[i].hour}:${this.minuteList[j].minute}:${this.secondList[k].second}`
              let the_currentTime_seconds = this.$moment.duration(currentTime).as('seconds') - 6 * 60 * 60 // 需要减去6个小时;
              let the_earliest_limitTime_secondes = this.getLimitTimeToSeconds()
              if(the_currentTime_seconds < the_earliest_limitTime_secondes) {
                this.hourList[i].disabled = true
                this.secondList[k].disabled = true
              } else {
                this.hourList[i].disabled = false
                this.secondList[k].disabled = false
              }
              if(the_currentTime_seconds >= 24 * 60 * 60) {
                this.hourList[i].disabled = true
                this.secondList[k].disabled = true
              }
            }
            break
          }
        }
      }
    },
    initMinuteDisableItem() {
      let currentTime = ''
      for(let i = 0; i < this.hourList.length; i++) {
        if(this.hourList[i].hour == this.hours) {
          for(let j = 0; j < this.minuteList.length; j++) {
            for(let k = 0; k < this.secondList.length; k++) {
              currentTime = `${this.hourList[i].hour}:${this.minuteList[j].minute}:${this.secondList[k].second}`
              let the_currentTime_seconds = this.$moment.duration(currentTime).as('seconds') - 6 * 60 * 60 // 需要减去6个小时;
              let the_earliest_limitTime_secondes = this.getLimitTimeToSeconds()
              if(the_currentTime_seconds < the_earliest_limitTime_secondes) {
                this.minuteList[j].disabled = true
                this.secondList[k].disabled = true
              } else {
                this.minuteList[j].disabled = false
                this.secondList[k].disabled = false
              }
              if(the_currentTime_seconds >= 24 * 60 * 60) {
                this.minuteList[j].disabled = true
                this.secondList[k].disabled = true
              }
            }
          }
          break
        }
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
.el-time-spinner__wrapper {
  width: 33.3%;
}
</style>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,332评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,508评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,812评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,607评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,728评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,919评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,071评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,802评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,256评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,576评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,712评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,389评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,032评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,026评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,473评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,606评论 2 350

推荐阅读更多精彩内容