vue element时间选择不能超过今天 时间选中长度不能超过7天

背景:

使用elenmet plus 组件实现时间选择;且日期时间选择不能超过今天;连续选中时间的长度范围不能超过7天

效果展示:

 

 

实现思路:

一、使用element组件自带的属性和方法;

:disabled-date="disabledDate"

@calendar-change="calendarChange"

@blur="handleBlur" 

二、使用js方法判断,通过时间组件选择的时间范围value值是否符合条件。

一、element日期时间组价

布局代码:

//布局代码
<el-date-picker 
    v-model="data.valueTwoTimer" 
    type="datetimerange"
    value-format="YYYY-MM-DD HH:mm:ss" 
    range-separator="至" 
    start-placeholder="开始时间"
    end-placeholder="结束时间" 
    :unlink-panels="true" 
    :default-time="data.valueTwoTimer"
    :disabled-date="disabledDate" 
    @calendar-change="calendarChange"     
    @blur="handleBlur" 
/>

核心属性和方法:

:disabled-date="disabledDate" @calendar-change="calendarChange" @blur="handleBlur" 

//vue3的写法
<script setup>
import { onMounted, reactive } from "vue";
const calendarChange = (dates) => {
    let hasSelectDate = dates !== null && dates.length > 0;
    data.minTime = hasSelectDate ? dates[0] : null;
};
const disabledDate = (time) => {
    const timeRange = 1 * 24 * 60 * 60 * 1000; // 1天时间戳
    const tempTime = Date.now() - timeRange;
    //是否触发calendarChange() 
    if (data.minTime) {
        const minTime = new Date(data.minTime).getTime();
        const maxTime = new Date(data.minTime).getTime() + timeRange * 6;// 最大选择7天时间
        if (tempTime < maxTime) {
            return time.getTime() < minTime || time.getTime() > tempTime;
        }
        return time.getTime() < minTime || time.getTime() > maxTime;
    } else {
        return time.getTime() >= tempTime;//不能超过今天
    }
};
const handleBlur = () => {
    data.minTime = null;
};
</script>

二、自定义的js方法判断 

自定义一个判断最大选择7天时间的方法。调取接口时触发此方法、或者时间选择完毕后触发此方法等。

//最大7天
const timeLimite = () => {
      const minTime = timeToTimestamp(times[0]);
      const maxTime = timeToTimestamp(times[1]);
      const isOver7 = maxTime - minTime > timeRange * 7;
      if (isOver7) {
        ElMessage({
          type: "warning",
          message: `历史记录查询时间不能超过7天`,
        });
        return false;
      }
}
const timeRange = 1 * 24 * 60 * 60 * 1000; // 1天时间戳
const timeToTimestamp = (time) => {
  let timestamp = Date.parse(new Date(time).toString());
  return timestamp;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值