el-date-picker时间选择器限制时间跨度为3天 - 详解

  1. 设置默认的开始与结束时间
  2. 处理结束时间,限制只查3天内的数据
// 下面代码中只写了关键的代码
<template>
  <el-date-picker
  v-model="time"
  type="datetimerange"
  range-separator="至"
  start-placeholder="开始日期"
  end-placeholder="结束日期"
  @change="handleTimeChange"
  >
  </template>
    <script>
      export default {
      data() {
      return {
      time: [new Date(), new Date()],
      }
      },
      created() {
      this.setDefaultTime();
      },
      methods: {
      // 设置默认时间范围为当天的开始和结束时间
      setDefaultTime() {
      const now = new Date();
      const startOfDay = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate(),
      0,
      0,
      0
      );
      const endOfDay = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate(),
      23,
      59,
      59
      );
      this.time = [startOfDay, endOfDay];
      this.handleTimeChange(); // 触发时间选择器方法
      },
      handleTimeChange() {
      const start = this.time[0];
      const end = this.time[1];
      // 限制时间跨度最多三天(开始时间的0点到第四天的0点)
      const maxEnd = new Date(start.getTime() + 3 * 24 * 60 * 60 * 1000); // 三天后的日期
      if (end > maxEnd) {
      this.time[1] = maxEnd; // 限制结束时间,真正的结束时间
      }
      // 下面可加查询等其他需要的逻辑代码或方法
      },
      }
      }
      </script>
posted @ 2025-09-19 09:20  yxysuanfa  阅读(26)  评论(0)    收藏  举报