【Vue】可以自定义回显格式的日期选择控件(日月周季年)

一、组件特点

基于element ui的datePicker的二次封装。两个特点:
1. 回显格式可以自定义
element ui的控件控制回显的属性为format,但是只能包含一个日期对象。
在这里插入图片描述
业务需要展示为两个日期段,如:选择 一月,展示为 2020-01-01 ~ 2020-01-31。该组件采用一个假的input框通过css覆盖到原始的datePicker的input框上,然后可以自定义回显内容。
2. 同一个组件支持日、月、周、季、年的切换
在这里插入图片描述
element ui官方文档上没有季的选项
在这里插入图片描述
但是实际上,通过查看element源码发现有部分quater的代码,且dom可以发现element里面有quater的面板,通过把type设置为quater可以调出季度选择的面板。
该组件通过修改element的shortCut类型面板,实现了在同一个组件内切换日月周季年的功能。

二、代码补充说明

  1. dateChange函数接入element暴露出来的选择日期之后的回调。
    该函数中,按照业务需要处理了日期: 选择的日期不能包含今天以及今天以后的日期。如果选择时间段的结束日期超过了今天,则结束时间采用昨天替代
  2. 笔者偷懒没有写通用的css,需要自己补充css部分,将假的input覆盖到真的input上去。注意要让假input的z-index高于原生的input框

三、代码

<template>
    <div class="container">
      <el-date-picker
        ref="refDatePicker"
        v-model="datePickerTime"
        :type="dateType"
        placeholder="选择日期"
        :picker-options="pickerOptions"
        popper-class="datePicker"
        @change="dateChange"
      />
      <el-input
        v-model="myInput"
        type="text"
        class="copyInput"
        suffix-icon="el-icon-date"
        placeholder="请输入内容"
        @click.native="onInputFocus"
      />
    </div>
  </template>
  
  <script>
  export default {
    props: {
      mulDateType: {
        type: String,
        default: ''
      },
      config: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      const clickFuncGenerator = (picker, type, text) => {
        this.dateType = type
        picker.$emit('pick', new Date())
        setTimeout(() => {
          this.$refs.refDatePicker.focus()
          this.active(text)
        }, 200)
      }
      return {
        dateType: 'date',
        startTime: '',
        endTime: '',
        datePickerTime: '', // 控件日期
        myInput: '', // 输入框日期
        pickerOptions: {
          firstDayOfWeek: 1,
          disabledDate: (time) => {
            return time.getTime() > Date.now() - 24 * 3600 * 1000
          },
          shortcuts: [{
            text: '日',
            onClick: picker => clickFuncGenerator(picker, 'date', '日')
          }, {
            text: '周',
            onClick: picker => clickFuncGenerator(picker, 'week', '周')
          }, {
            text: '月',
            onClick: picker => clickFuncGenerator(picker, 'month', '月')
          }, {
            text: '季',
            onClick: picker => clickFuncGenerator(picker, 'quarter', '季')
          }, {
            text: '年',
            onClick: picker => clickFuncGenerator(picker, 'year', '年') }]
        }
      }
    },
    mounted() {
      this.dateType = this.config.mulDateType || 'date'
      this.startTime = this.config.startTime
      this.endTime = this.config.endTime
      this.myInput = '' // 取消输入框回显
    },
    methods: {
      // 激活组件左边快捷选项的状态
      active(str) { // 传入中文或英文都可以
        const map = { date: '日', month: '月', week: '周', quarter: '季', year: '年' }
        const zh = map[str] || str
        const doms = document.getElementsByClassName('el-picker-panel__shortcut')
        Array.from(doms).forEach(dom => {
          if (dom.innerText === zh) { // dom的innerText是中文
            dom.classList.add('date-picker-selected-shortcut')
          }
        })
      },
      // 时间控件的change事件
      dateChange(val) {
        const dateObj = new Date(val)
        const today = {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          date: new Date().getDate()
        }
        const todayTs = new Date(today.year + '-' + today.month + '-' + today.date).getTime()
        const yesterday = this.$moment(new Date().getTime() - 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
        // 传入一个日期对象,返回该日期对象当月的总天数。  如:getLastDay(new Date('2020-11-02'))  =>  31
        const getLastDay = (date) => {
          const dateObj = new Date(date)
          const month = dateObj.getMonth()
          const year = dateObj.getFullYear()
          const lastDay = new Date(new Date(year, month + 1, 1).getTime() - 1000 * 60 * 60 * 24)
          return lastDay.getDate()
        }
        if (this.dateType === 'date') {
          this.startTime = this.$moment(dateObj).format('YYYY-MM-DD') === this.$moment(new Date()).format('YYYY-MM-DD') ? yesterday : this.$moment(dateObj).format('YYYY-MM-DD')
          this.endTime = this.startTime
          this.myInput = this.endTime
        } else if (this.dateType === 'month') {
          this.startTime = this.$moment(dateObj).format('YYYY-MM') + '-01'
          const shortTime = this.$moment(dateObj).format('YYYY-MM') + '-' + getLastDay(dateObj)
          this.endTime = todayTs < new Date(shortTime).getTime() ? yesterday : shortTime
          this.myInput = this.startTime + ' ~ ' + this.endTime
        } else if (this.dateType === 'week') {
          if (dateObj.getDay() === 1) { // 传入的是周一(该情况只会在今天为周一的时候触发)
            this.startTime = this.$moment(dateObj.getTime() - 24 * 3600 * 1000 * 7).format('YYYY-MM-DD')
            this.endTime = this.$moment(dateObj.getTime() - 24 * 3600 * 1000).format('YYYY-MM-DD')
          } else { // 手动选择日期,element总是让dateObj为周二(如果今天不是周一,选择其他周一,dateObj也是周二)
            const temp1 = new Date(dateObj.getTime() - 24 * 3600 * 1000 * (dateObj.getDay() - 1))
            const temp2 = new Date(new Date(temp1).getTime() + 24 * 3600 * 1000 * 6)
  
            this.startTime = this.$moment(temp1).format('YYYY-MM-DD')
            const shortTime = this.$moment(temp2).format('YYYY-MM-DD')
            this.endTime = todayTs < new Date(shortTime).getTime() ? yesterday : shortTime
          }
          this.myInput = this.startTime + ' ~ ' + this.endTime
        } else if (this.dateType === 'quarter') {
          const month = dateObj.getMonth()
          const year = dateObj.getFullYear()
          const startMonth = (month / 3) * 3 // 该季度的第一个月
          const endMonth = startMonth + 2 // 该季度的最后一个月
  
          const firstDay = new Date(year, startMonth, 1)
          const lastDay = new Date(new Date(year, endMonth + 1, 1).getTime() - 1000 * 60 * 60 * 24)
          this.startTime = this.$moment(firstDay).format('YYYY-MM-DD')
          const shortTime = this.$moment(lastDay).format('YYYY-MM-DD')
          this.endTime = todayTs < new Date(shortTime).getTime() ? yesterday : shortTime
          this.myInput = this.startTime + ' ~ ' + this.endTime
        } else if (this.dateType === 'year') {
          this.startTime = dateObj.getFullYear() + '-01-01'
          const shortTime = dateObj.getFullYear() + '-12-31'
          this.endTime = todayTs < new Date(shortTime).getTime() ? yesterday : shortTime
          this.myInput = this.startTime + ' ~ ' + this.endTime
        }
        this.datePickerTime = this.endTime
        this.$emit('handleMuldate', { mulDateType: this.dateType, startTime: this.startTime, endTime: this.endTime })
      },
      // 假input框获取焦点时让原始日期组件获取焦点
      onInputFocus() {
        this.$refs.refDatePicker.focus()
        this.$nextTick(() => {
          this.active(this.dateType)
        })
      }
    }
  }
  </script>

转载请注明原文链接,谢谢

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值