element-ui年份范围选择器

故事背景: 接着上次自定义单行文本输入框需求, 还有一个自定义日期的需求, 需要支持选择年, 年月, 年月日, 年月日时, 年月日时分, 同时还要支持上面类型日期区间选择。这个需求的难点在于其他所有类型 element-ui 都有对应的组件, 但是唯独年份范围选择器 element-ui 没有支持,咱也不知道为啥饿了吗团队没有写! 产品现在需要这样的功能, 我们总不至于说第三方库不支持吧, 老脸搁不下, 同时之前也有被小伙伴问过怎么自己实现一个类似 element-ui 年份区间的选择器, 花了半天时间, 我们也勉勉强强实现了这个需求, 趁着五一稍微闲点, 我们把代码整理了下,现在贴出来供大家查考。后期会考虑放到 npm 上, 供大家更方便使用。
配置日期选择器页面如下:

image.png

我们实现效果如下:
Kapture 2022-05-01 at 01.57.51.gif

使用注意事项:

  • 此组件基于 element-ui 组件 & 样式(el-popover & el-date-editor 样式), 所以项目ui 框架必须是 element-ui
  • 组件功能目前还比较弱, v-model只支持绑定 Array 类型, 一些事件也不支持, 本人后期会根据阅读量和读者反馈加入一些需要功能
下面直接上代码块, 直接 copy 就可使用。
<template>
  <el-popover
    ref="popover"
    placement="bottom"
    v-model="showPanel"
    popper-class="custom_year_range"
    trigger="manual"
    v-clickoutside="() => { showPanel = false }"
  >
    <div class="_inner floatPanel">
      <div class="_inner leftPanel">
        <div class="_inner panelHead">
          <i
            class="_inner el-icon-d-arrow-left"
            @click="onClickLeft"
          ></i>
          <span>
            {{ leftYearList[0] + '年 ' + '- ' + leftYearList[9] + '年' }}
          </span>
        </div>
        <div class="_inner panelContent">
          <div
            :class="{
              oneSelected: item === startYear && oneSelected,
              startSelected: item === startYear,
              endSelected: item === endYear,
              betweenSelected: item > startYear && item < endYear,
            }"
            v-for="item in leftYearList"
            :key="item"
          >
            <a
              :class="{
                cell: true,
                _inner: true,
                selected: item === startYear || item === endYear,
              }"
              @click="onClickItem(item)"
              @mouseover="onHoverItem(item)"
            >
              {{ item }}
            </a>
          </div>
        </div>
      </div>
      <div class="_inner rightPanel">
        <div class="_inner panelHead">
          <i
            class="_inner el-icon-d-arrow-right"
            @click="onClickRight"
          ></i>
          <span>{{ rightYearList[0] + '年 ' + '- ' + rightYearList[9] + '年' }}</span>
        </div>
        <div class="_inner panelContent">
          <div
            :class="{
              startSelected: item === startYear,
              endSelected: item === endYear,
              betweenSelected: item > startYear && item < endYear,
            }"
            v-for="item in rightYearList"
            :key="item"
          >
            <a
              :class="{
                cell: true,
                _inner: true,
                selected: item === endYear || item === startYear,
              }"
              @click="onClickItem(item)"
              @mouseover="onHoverItem(item)"
            >
              {{ item }}
            </a>
          </div>
        </div>
      </div>
    </div>
    <div slot="reference">
      <div
        ref="yearPicker"
        style="width: 100%"
        class="el-date-editor el-range-editor el-input__inner el-date-editor--daterange el-range-editor--small"
      >
        <i class="el-input__icon el-range__icon el-icon-date"></i>
        <input
          class="_inner range_input"
          ref="inputLeft"
          type="text"
          name="yearInput"
          placeholder="选择开始年份"
          v-model="startShowYear"
          @focus="onFocus"
          @keyup="handleInput('start')"
        />
        <span class="el-range-separator">{{ sp }}</span>
        <input
          class="_inner range_input"
          ref="inputRight"
          type="text"
          name="yearInput"
          placeholder="选择结束年份"
          v-model="endShowYear"
          @focus="onFocus"
          @keyup="handleInput('end')"
        />
      </div>
    </div>
  </el-popover>
</template>

<script>
import moment from 'moment'
import { clickoutside, SELECT_STATE } from '@/views/customerLists/components/custom/customView/components/utils.js'
export default {
  name: 'yearPicker',
  directives: { clickoutside },
  computed: {
    oneSelected() {
      return this.curState === SELECT_STATE.selecting && (this.startYear === this.endYear || this.endYear == null)
    },
    leftYearList() {
      return this.yearList.slice(0, 10)
    },
    rightYearList() {
      return this.yearList.slice(10, 20)
    }
  },
  props: {
    sp: {
      default: '至'
    },
    value: {
      default: null
    }
  },
  data() {
    return {
      itemBg: {},
      startShowYear: null,
      endShowYear: null,
      yearList: [],
      showPanel: false,
      startYear: null,
      endYear: null,
      curYear: 0,
      curSelectedYear: 0,
      curState: SELECT_STATE.unselect
    }
  },
  methods: {
    handleInput(type) {
      switch (type) {
        case 'start':
          if (isNaN(this.startShowYear)) {
            this.startShowYear = this.startYear
            return
          }
          this.startYear = this.startShowYear * 1
          break
        case 'end':
          if (isNaN(this.endShowYear)) {
            this.endShowYear = this.endYear
            return
          }
          this.endYear = this.endShowYear * 1
          break
      }
      [this.startYear, this.endYear] = [this.endYear, this.startYear]
      this.startShowYear = this.startYear
      this.endShowYear = this.endYear
    },

    onHoverItem(iYear) {
      if (this.curState === SELECT_STATE.selecting) {
        const tmpStart = this.curSelectedYear
        this.endYear = Math.max(tmpStart, iYear)
        this.startYear = Math.min(tmpStart, iYear)
      }
    },

    async onClickItem(selectYear) {
      if (
        this.curState === SELECT_STATE.unselect ||
        this.curState === SELECT_STATE.selected
      ) {
        this.startYear = selectYear
        this.curSelectedYear = selectYear
        this.endYear = null
        this.curState = SELECT_STATE.selecting
      } else if (this.curState === SELECT_STATE.selecting) {
        this.endShowYear = this.endYear || this.startYear
        this.startShowYear = this.startYear
        this.curState = SELECT_STATE.selected
        await this.$nextTick()
        this.showPanel = false
        this.$parent?.$parent?.$parent?.$parent?.$parent.clearValidate?.()
      }
    },

    async onFocus() {
      await this.$nextTick()
      this.showPanel = true
    },

    updateYearList() {
      const startYear = ~~(this.curYear / 10) * 10
      console.log(startYear, this.curYear, 'this.curYearthis.curYearthis.curYear')
      this.yearList = []
      for (let index = 0; index < 20; index++) {
        this.yearList.push(startYear + index)
      }
    },

    onClickLeft() {
      this.curYear = this.curYear * 1 - 10
      this.updateYearList()
    },

    onClickRight() {
      this.curYear = this.curYear * 1 + 10
      this.updateYearList()
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val?.length === 0) return
        const [first, end] = val || []
        this.startShowYear = first
        this.endShowYear = end
      },
      immediate: true,
      deep: true
    },

    startShowYear: {
      handler(val) {
        this.$emit('input', [val, this.endShowYear || ''])
      },
      immediate: true,
      deep: true
    },

    endShowYear: {
      handler(val) {
        this.$emit('input', [this.startShowYear || '', val])
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    const [startYear, endYear] = this.value || []
    if (startYear) {
      this.startYear = Number(startYear)
      this.endYear = Number(endYear)
      this.curState = SELECT_STATE.selected
      this.curYear = startYear
    } else {
      this.curYear = moment().format('yyyy')
    }
    this.updateYearList()
  },

  mounted() {
    window.Vue = this
  }
}
</script>
<style lang="scss">
.custom_year_range {
  .floatPanel {
    > div {
      width: 50%;
    }
    padding: 0 16px;
    // position: absolute;
    display: flex;
    background-color: #fff;
    z-index: 2000;
    border-radius: 4px;
    width: 650px;
    height: 250px;
    top: 40px;
    left: -50px;
    .panelContent {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      height: calc(100% - 70px);
      .oneSelected {
        border-top-right-radius: 24px;
        border-bottom-right-radius: 24px;
      }
      .startSelected {
        background-color: #f2f6fc;
        border-top-left-radius: 24px;
        border-bottom-left-radius: 24px;
      }
      .endSelected {
        background-color: #f2f6fc;
        border-top-right-radius: 24px;
        border-bottom-right-radius: 24px;
      }
      .betweenSelected {
        background-color: #f2f6fc;
      }
      > div {
        width: 75px;
        height: 48px;
        line-height: 48px;
        margin: 3px 0;
        // border-radius: 24px;
        text-align: center;
        a {
          display: inline-block;
          width: 60px;
          height: 36px;
          cursor: pointer;
          line-height: 36px;
          border-radius: 18px;
          &:hover {
            color: #409eff;
          }
        }
        .selected {
          background-color: #409eff;
          color: #fff;
          &:hover {
            color: #fff !important;
          }
        }
      }
    }
    .panelHead {
      position: relative;
      height: 46px;
      line-height: 46px;
      text-align: center;
      display: flex;
      align-items: center;
      justify-content: center;
      span {
        font-size: 16px;
        font-weight: 500;
        padding: 0 5px;
        line-height: 22px;
        text-align: center;
        cursor: pointer;
        color: #606266;
        &:hover {
          color: #409eff;
        }
      }
      i {
        position: absolute;
        cursor: pointer;
        &:hover {
          color: #3e77fc;
        }
      }
    }
    .rightPanel {
      padding-left: 8px;
    }
    .leftPanel .panelHead i {
      left: 20px;
    }
    .rightPanel .panelHead i {
      right: 20px;
    }
  }
  .floatPanel::before {
    content: "";
    height: 100%;
    top: 0;
    position: absolute;
    left: 50%;
    width: 1px;
    border-left: 1px solid #e4e4e4;
  }
}
</style>
<style lang="scss" scoped>
.range_input {
  appearance: none;
  border: none;
  outline: 0;
  padding: 0;
  width: 39%;
  color: #606266;
  line-height: 1;
  height: 100%;
  margin: 0;
  text-align: center;
  display: inline-block;
}
.yearPicker {
  // font-size: 14px;
  // display: flex;
  // position: relative;
  // transition: all 0.3s;
  input:first-child {
    text-align: right;
  }
  .labelText {
    position: absolute;
    left: 8px;
  }
  background-color: #fff;
  span {
    padding: 0 8px;
    height: 32px;
    line-height: 32px;
  }
  border: 1px solid #eff1f3;
  height: 34px;
  line-height: 34px;
  border-radius: 4px;
  padding: 0 28px 0 8px;
  box-sizing: border-box;
}
input {
  width: 60px;
  border: none;
  height: 32px;
  line-height: 32px;
  box-sizing: border-box;
  background-color: transparent;
}
input:focus {
  outline: none;
  background-color: transparent;
}
.yearPicker:hover {
  border-color: #3e77fc;
}
.dateIcon {
  position: absolute;
  right: 16px;
  top: 9px;
  color: #adb2bc;
}
</style>
<!-- @/views/customerLists/components/custom/customView/components/utils.js -->
export const clickoutside = {
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身,是本身,则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding && binding.expression) {
        // 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法
        if (binding.value && binding.value(e)) {
          binding.value(e)
        }
      }
    }
    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler
    document.addEventListener('click', documentHandler)
  },
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.__vueClickOutside__)
    delete el.__vueClickOutside__
  }
}

export const SELECT_STATE = {
  unselect: 0,
  selecting: 1,
  selected: 2
}

如果用到了,希望给个赞, 小弟在这感激不尽

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,384评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,845评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,148评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,640评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,731评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,712评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,703评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,473评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,915评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,227评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,384评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,063评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,706评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,302评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,531评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,321评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,248评论 2 352

推荐阅读更多精彩内容