封装el-date-picker,选择某年某月某日时候,往前最多可选择6个月,往后也是最多只能选择6个月

<template>
  <el-date-picker
    v-model="timeData"
    type="daterange"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    :picker-options="pickerOption"
    value-format="yyyy-MM-dd"
    @change="handleChangeDate"
  ></el-date-picker>
</template>

<script>

import { resetData } from '@/utils'

export default {
  name: 'DaterangePicker',
  props: {
    month: {
      required: false,
      type: Number,
      default: 6
    },
    value: {
      required: false,
      default: () => { return [] },
      type: Array
    }
  },
  data: () => {
    return {
      timeData: [],
      startTime: '',
      pickerOption: {}
    }
  },
  watch: {
    value(val) {
      this.timeData = val
      this.resetOption()
      this.initPickerOption()
    }
  },
  created() {
    this.initPickerOption()
    this.timeData = this.value
  },
  methods: {
    initPickerOption() {
      this.pickerOption = {
        onPick: (time) => {
          this.startTime = time.minDate
          this.setDisabledDate()
        }
      }
    },
    setDisabledDate() {
      const fnc = (time) => {
        let currentTime = ''
        if (this.startTime) {
          currentTime = this.startTime
          const threeMonths = currentTime.setMonth(currentTime.getMonth() + this.month)
          currentTime.setMonth(currentTime.getMonth() - this.month)
          const lastMonths = currentTime.setMonth(currentTime.getMonth() - this.month)
          currentTime.setMonth(currentTime.getMonth() + this.month)
          return time.getTime() < lastMonths || time.getTime() > threeMonths
        }
      }
      this.$set(this.pickerOption, 'disabledDate', fnc)
    },
    resetOption() {
      resetData(this, 'pickerOption')
    },
    handleChangeDate(val) {
      this.timeData = val
      val || (this.startTime = '')
      this.resetOption()
      this.$emit('input', this.timeData)
      this.$emit('change', this.timeData)
    }
  }
}
</script>

<style scoped lang="scss">
  .el-date-editor{
    padding: 3px;
  }
</style>

举例:当前选择是2022年1.1,那么往前最多可以选择到2021.7.1,往后则最多可以选择到2022.7.1.非常实用。

以上是封装好的,项目中直接引用,

<daterange-picker :value="rangeTime" :month="6" @change="handleChangeDate"></daterange-picker>


data(){
return:{
rangeTime:[]
}
},

methods:{ 
handleChangeDate(val) {
      if (val) {
        this.searchParams.startTime = val[0]
        this.searchParams.endTime = val[1]
      } else {
        this.searchParams.startTime = ''
        this.searchParams.endTime = ''
      }
    },
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值