基于vue和ElementUI时间选择控件的封装

基于vue和ElementUI时间选择控件的封装

最近有个需求就是需要把查询控制在最近六个月,还要要求时间的可选范围,在网上找了好久都没有找到,于是就自己动手写了一个,希望对大家有所帮助,也是记录自己的第一次博客。
先看一下效果
在这里插入图片描述
这里是选择日期范围
在这里插入图片描述
在这里插入图片描述
根据所选日期限定可选时间,演示一个点击过去一周查看效果
在这里插入图片描述
下面是代码 代码片段

// An highlighted block
<template>
  <div style="border-radius:5px;height:33px;width:348px">
    <el-popover v-model="showPopover">
      <div>
        <div style="margin-top:5px;text-align:center;">
          <span>选择日期</span>
          <el-date-picker
            size="mini"
            v-model="beginDate"
            type="datetime"
            style="width:180px"
            value-format="yyyy-MM-dd HH:mm:ss"
            :picker-options="beginDateOptions"
            placeholder="选择日期时间"
          ></el-date-picker>
          <span></span>
          <el-date-picker
            size="mini"
            v-model="finalDate"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            style="width:180px"
            placeholder="结束时间"
            :picker-options="fianlDateOptions"
          ></el-date-picker>
        </div>
        <div style="margin-top:5px;position:relative;left:50px">
          <el-row style="width:480px">
            <el-col :span="12">
              <el-button size="mini" type="text" @click="setDay(0)">今天</el-button>
            </el-col>
            <el-col :span="12" :pull="6">
              <el-button size="mini" type="text" @click="setDay(-1, true)">昨天</el-button>
            </el-col>
            <el-col :span="12">
              <el-button size="mini" type="text" @click="setDay(-7)">过去一周</el-button>
            </el-col>
            <el-col :span="12" :pull="6">
              <el-button size="mini" type="text" @click="setDay(-14)">过去两周</el-button>
            </el-col>
            <el-col
              :span="12"
              v-for="(m,index) in getMouth()"
              :key="index"
              :pull="(index+1)%2 == 0?6:0"
            >
              <el-button size="mini" type="text" @click="getformartDay(m)">{{m}}</el-button>
            </el-col>
          </el-row>
        </div>
        <hr style="border:1px solid #f0f0f0;margin: 5px 20px;" />
        <div style="text-align:right">
          <el-button size="mini" @click="showPopover = false">取消</el-button>
          <el-button type="primary" size="mini" @click="showPopover = false;handleConfirm()">确定</el-button>
        </div>
      </div>
      <div slot="reference" style="width:450px;display:inline-bloack">
        <el-input
          size="small"
          v-model="startDateInput"
          class="popover-input"
          placeholder="请选择日期"
          clearable
          @clear="handleConfirmClear(1)"
        ></el-input>
        <span></span>
        <el-input
          size="small"
          v-model="endDateInput"
          class="popover-input"
          placeholder="请选择日期"
          clearable
          @clear="handleConfirmClear(2)"
        ></el-input>
      </div>
    </el-popover>
  </div>
</template>
<script>
import dateUtil from "@/utils/dateutil.js";

export default {
  props: {
    startDate: String,
    endDate: String
  },
  data() {
    return {
      beginDate: "",
      finalDate: "",
      showPopover: false,
      timeSpace: 0,
      startDateInput: "",
      endDateInput: "",
      beginDateOptions: {
        disabledDate: time => {
          return (
            time.getTime() > this.changeTimeOne() ||
            time.getTime() < this.changeTime()
          );
        }
      },
      fianlDateOptions: {
        disabledDate: time => {
          return (
            time.getTime() > this.changeTimeOne() ||
            time.getTime() < this.changeTime()
            //   new Date(this.beginDate).getTime() - 24 * 3600 * 1000
            // time.getTime() < new Date(this.timeSpace).getTime()
          );
        }
      }
    };
  },

  created() {},
  computed: {},
  methods: {
    handleConfirm() {
      this.startDateInput = this.beginDate;
      this.endDateInput = this.finalDate;
      let value = [this.beginDate, this.finalDate];
      this.$emit("afterDateSelect", value);
    },
    handleConfirmClear(type) {
      if (type == 1) {
        this.startDateInput = "";
      } else if (type == 2) {
        this.endDateInput = "";
      }
      let value = [this.startDateInput, this.endDateInput];
      this.$emit("afterDateSelect", value);
    },
    changeTimeOne() {
      if (this.timeSpace == -1) {
        return new Date(this.beginDate).getTime();
      } else {
        return Date.now();
      }
    },
    changeTime() {
      if (this.timeSpace == 1) {
        return new Date(this.beginDate).getTime() - 24 * 3600 * 1000;
      } else {
        return new Date().getTime() + (this.timeSpace - 1) * 24 * 3600 * 1000;
      }
    },
    // 过去几天
    setDay(day, isSingleDay) {
      this.timeSpace = day;
      if (day == -1 || day == 0) {
        this.beginDate = dateUtil.getDay(day, "beginDate");
      } else {
        this.beginDate = dateUtil.getDay(day);
      }
      if (isSingleDay) {
        this.finalDate = dateUtil.getDay(day, "finalDate");
      } else {
        this.finalDate = dateUtil.getDay(0);
      }
    },
    getformartDay(m) {
      this.timeSpace = 1;
      m = m.replace("年", "-");
      m = m.replace("月", "");
      let year = m.split("-")[0];
      let month = m.split("-")[1];
      month = month.replace("0", "");
      this.beginDate = dateUtil.getMonthStartDate(year, month - 1);
      this.finalDate = dateUtil.getMonthEndDate(year, month - 1);
    },
    getMouth() {
      let datelist = [];
      let date = new Date();
      let Y = date.getFullYear();
      let M = date.getMonth() + 1;
      for (let i = 0; i < 6; i++) {
        let dateoption = "";
        if (M - 1 !== 0) {
        } else {
          M = 12;
          Y = Y - 1;
        }
        let m = M;
        m = m < 10 ? "0" + m : m;
        dateoption = Y + "年" + m + "月";
        M--;
        datelist.push(dateoption);
      }
      return datelist;
    }
  },
  mounted() {
    // this.beginDate = this.startDate ? this.startDate : dateUtil.getDay(0);
    // this.finalDate = this.endDate ? this.endDate : dateUtil.getDay(0);
  }
};
</script>

<style lang="scss" scoped>
.popover-input {
  border: none;
  height: 100%;
  width: 180px;
  //   padding-left: 15px;
  //   position: relative;
  //   top: -2px;
  //   border-radius: 5px;
  //   font-size: 13px;
}
</style>

下面是代码 dateutil.js

// An highlighted block
var now = new Date(); //当前日期 
var nowDayOfWeek = now.getDay(); //今天本周的第几天 
var nowDay = now.getDate(); //当前日 
var nowMonth = now.getMonth(); //当前月 
var nowYear = now.getYear(); //当前年 
nowYear += (nowYear < 2000) ? 1900 : 0; //

var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastYear = lastMonthDate.getYear();
var lastMonth = lastMonthDate.getMonth();

let dateUtil = {
    // 获取几天前/后的日期
    getDay: function (day, isSingleDay) {
        var today = new Date();
        var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
        today.setTime(targetday_milliseconds); //注意,这行是关键代码
        var tYear = today.getFullYear();
        var tMonth = today.getMonth();
        var tDate = today.getDate();
        var h = today.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = today.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = today.getSeconds();
        second = second < 10 ? "0" + second : second;
        tMonth = this.doHandleMonth(tMonth + 1);
        tDate = this.doHandleMonth(tDate);
        if (isSingleDay) {
            if (isSingleDay == 'finalDate') {
                return tYear + "-" + tMonth + "-" + tDate + ' ' + '23' + ':' + '59' + ':' + '59';
            } else {
                return tYear + "-" + tMonth + "-" + tDate + ' ' + '00' + ':' + '00' + ':' + '00';
            }
        } else {
            return tYear + "-" + tMonth + "-" + tDate + ' ' + h + ':' + minute + ':' + second;
        }
    },
    doHandleMonth: function (month) {
        var m = month;
        if (month.toString().length == 1) {
            m = "0" + month;
        }
        return m;
    },

    //格式化日期:yyyy-MM-dd 
    formatDate: function (date) {
        var myyear = date.getFullYear();
        var mymonth = date.getMonth() + 1;
        var myweekday = date.getDate();

        if (mymonth < 10) {
            mymonth = "0" + mymonth;
        }
        if (myweekday < 10) {
            myweekday = "0" + myweekday;
        }
        return (myyear + "-" + mymonth + "-" + myweekday);
    },

    //获得某月的天数 
    getMonthDays: function (myMonth) {
        var monthStartDate = new Date(nowYear, myMonth, 1);
        var monthEndDate = new Date(nowYear, myMonth + 1, 1);
        var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
        return days;
    },

    //获得本周的开始日期 
    getWeekStartDate: function () {
        var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
        return this.formatDate(weekStartDate);
    },

    //获得本周的结束日期 
    getWeekEndDate: function () {
        var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
        return this.formatDate(weekEndDate);
    },

    // //获得本月的开始日期 
    // getMonthStartDate: function () {
    //     var monthStartDate = new Date(nowYear, nowMonth, 1);
    //     return this.formatDate(monthStartDate);
    // },

    // //获得本月的结束日期 
    // getMonthEndDate: function () {
    //     var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays(nowMonth));
    //     return this.formatDate(monthEndDate);
    // },

    //获得本月的开始日期 
    getMonthStartDate: function (year, month) {
        var monthStartDate = new Date(year, month, 1);
        return this.formmatGetDay(monthStartDate);
    },

    //获得本月的结束日期 
    getMonthEndDate: function (year, month) {
        var monthEndDate = new Date(year, month, this.getMonthDays(month));
        return this.formmatGetDay(monthEndDate);
    },
    // 格式化某个月的开始或结束时间
    formmatGetDay: function (today) {
        // var today = new Date();
        // var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
        // today.setTime(targetday_milliseconds); //注意,这行是关键代码
        var tYear = today.getFullYear();
        var tMonth = today.getMonth();
        var tDate = today.getDate();
        var h = today.getHours();
        h = h < 10 ? "0" + h : h;
        var minute = today.getMinutes();
        minute = minute < 10 ? "0" + minute : minute;
        var second = today.getSeconds();
        second = second < 10 ? "0" + second : second;
        tMonth = this.doHandleMonth(tMonth + 1);
        tDate = this.doHandleMonth(tDate);
        return tYear + "-" + tMonth + "-" + tDate + ' ' + h + ':' + minute + ':' + second;
        // if (isSingleDay) {
        //     if (isSingleDay == 'finalDate') {
        //         return tYear + "-" + tMonth + "-" + tDate + ' ' + '23' + ':' + '59' + ':' + '59';
        //     } else {
        //         return tYear + "-" + tMonth + "-" + tDate + ' ' + '00' + ':' + '00' + ':' + '00';
        //     }
        // } else {
        //     return tYear + "-" + tMonth + "-" + tDate + ' ' + h + ':' + minute + ':' + second;
        // }
    },

    //获得上月开始时间
    getLastMonthStartDate: function () {
        var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
        return this.formatDate(lastMonthStartDate);
    },

    //获得上月结束时间
    getLastMonthEndDate: function () {
        var lastMonthEndDate = new Date(nowYear, lastMonth, this.getMonthDays(lastMonth));
        return this.formatDate(lastMonthEndDate);
    }
}

export default dateUtil

下面是引用组件

// An highlighted block
import selectdate from "@/components/selectdate";
<el-form-item label="创建时间">
  <selectdate @afterDateSelect="afterDateSelect" :endDate="endDt" :startDate="startDt" /> 
</el-form-item>

//在data中定义日期范围
// 日期范围
startDate: "",
endDt: "",
dateRange: "",
//在methods中定义回调方法
afterDateSelect(time) {
      console.log(time);
      this.dateRange = time;
    },

这样就完成了,大家可以测试一下,很好用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值