Vue日期时间选择器组件使用方法详解

本文实例为大家分享了Vue日期时间选择器组件的具体代码,供大家参考,具体内容如下

1.效果图如下

单选日期选择器

多选日期选择器

日期时间选择器

2.准备

Date原型格式化工具方法

Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

根据传入时间日期解析出该月份,获取该月的第一天和最后一天的时间戳,和该月时间戳对应的星期
【注意】

  • 一定要解析该月份第一天的零点零分,js大部分日期解析为那天的8点,但有些日期会解析为那天的零点零分,这样就会出现时间戳错误,导致获取该月份天数错误
  • 因为一般显示该月份是包含上月或者下个月的一些在该月星期的日期,所以也要计算出该月包含的几个星期的天
getMonthDay() {
  //该月第一天
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();
//下个月第一天减去1s为该月最后一天时间
      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }
//计算该月包含的星期,并获取对应星期的第一天
      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
//获取对应的该月天数
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
},

3.具体实现

SCSS样式

 .date-picker-bg {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 5;
}

.date-picker {
  background-color: white;
  position: fixed;
  display: block;
  padding: 4px;
  z-index: 6;
  border: solid 1px gainsboro;
  border-radius: 2px;
  .picker-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 30px;
    line-height: 30px;
    .picker-arrow {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width:30px;
      height: 30px;
      cursor: pointer;
      .iconfont {
        color: #8a8a8a;
      }
      .iconfont:active,
      .iconfont:hover {
        color: #388dea;
      }
    }

    .date-text {
      flex: 1;
      font-weight: bold;
      display: inline-block;
      text-align: center;
      font-size: 14px;
    }
  }

  .picker-content {
    display: block;
    border-top: solid 1px gainsboro;
    border-bottom: solid 1px gainsboro;
    height: 160px;
    table {
      width: 100%;
      border-collapse: collapse;
      border-spacing: 0;
      font-size: 12px;
      line-height: 20px !important;
      thead > tr {
        background-color: #cedeee;
        th {
          text-align: center;
          font-weight: normal;
        }
      }
      tbody {
        tr {
          td {
            font-weight: 600;
            cursor: pointer;
            text-align: center;
          }
          td.gray {
            font-weight: normal;
            color: #8a8a8a;
          }
          td.active {
            color: white;
            background: #388dea;
          }
        }
      }
    }
  }

  .picker-content1 {
    @extend .picker-content;
    display: flex;
    flex-direction: row;
    table {
      width: calc(100% - 40px);
    }
    .hour-list {
      display: inline-block;
      list-style: none;
      padding: 0;
      margin: 0;
      height: 100%;
      overflow-x: hidden;
      width: 40px;
      font-size:12px;

      overflow-y: auto;
      li {
        padding: 0;
        margin: 0;
        display: flex;
        align-items: center;
        padding: 0 4px;
        height:20px;
        cursor: pointer;
      }
      li:not(:last-child) {
        border-bottom: solid 1px gainsboro;
      }
      li.active {
        color: white;
        background: #388dea;
      }
    }
    .hour-list::-webkit-scrollbar {
      background: transparent;
      height: 8px;
      width:8px;
      border: none;
    }

    .hour-list::-webkit-scrollbar-thumb {
      background: lightgray;
      border-radius:5px;
    }
    //设置滚动条 end
  }

  .picker-footer {
    display: block;
   line-height: 30px;
   text-align: right;
   white-space: nowrap;
    button {
      outline: none;
      border: solid 1px gainsboro;
      border-radius: 2px;
      color: #8a8a8a;
      height: 24px;
      font-size: 12px;
      background-color: #f3f3f3;
    }
    button:active,
    button:hover {
      border-color: #388dea;
      color: #388dea;
      background-color: #d9edf6;
    }
  }
}

单选日期选择器DatePicker

 <template>
  <div style="display:inline-block">
    <span @click="showPicker">{{getLangText(label.datePicker)}}</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div
      class="date-picker"
      v-show="isShow"
      :style="{width:'220px',top:pickerTop>0?pickerTop+'px':''}"
    >
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
        <!--生成对应的月份星期表格 start-->
      <div class="picker-content">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',selectDate==monthList[idx-1][m-1]?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
                @dblclick="onConfirmDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
              <!--日期为该月为深色否则为浅色-->
            </tr>
          </tbody>
        </table>
      </div>
        <!--生成对应的月份星期表格 end-->
      <div class="picker-footer">
        <button @click="closePicker">{{getLangText(label.close)}}</button>
        <button @click="setNow">{{getLangText(label.today)}}</button>
        <!-- <button @click="confirmPicker">{{getLangText(label.ok)}}</button> -->
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default {
  name: "DatePicker",
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem("langType")
    },
    date: {
      type: String,
      default: new Date().format("yyyy-MM-dd")
    },
    isScroll: {
      type: Boolean,
      default: false
    },
     isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({
    label: {
      ok: { zh: "确定", en: "OK" },
      close: { zh: "关闭", en: "close" },
      today: { zh: "今天", en: "today" },
      datePicker: { zh: "日期选择", en: "DatePicker" }
    },
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "一", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    pickerTop: 0
  }),
  watch: {
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    showPicker(e) {
      if (this.isScroll) {
        this.pickerTop = e.clientY + e.offsetY;
        var h = document.getElementById("app").offsetHeight;
        if (this.pickerTop > h - 230) {
          this.pickerTop = h - 230;
        }
      }

       this.$emit("update:is-show",true);
      var time = new Date(this.date).getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    confirmPicker() {
      this.$emit("update:date", new Date(this.selectDate).format("yyyy-MM-dd"));
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.$emit("update:date", new Date(time).format("yyyy-MM-dd"));
    }
  },
  mounted() {
    this.getMonthDay();
  }
};
</script>
<style lang="scss" scoped>
</style>

多选日期选择器DatePicker1

<template>
  <div style="display:inline-block">
    <span @click="showPicker">日期选择</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div class="date-picker" v-show="isShow" style="width:220px">
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
      <!--生成对应的月份星期表格 start-->
      <div class="picker-content">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',getSelectDate(monthList[idx-1][m-1])?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
               <!--日期为该月为深色否则为浅色-->
            </tr>
          </tbody>
        </table>
      </div>
       <!--生成对应的月份星期表格 end-->
      <div class="picker-footer">
        <button @click="onFullMonth">整月</button>
        <button @click="onSelectDate(new Date(new Date().format('yyyy-MM-dd 00:00')).getTime())">今天</button>
        <button @click="closePicker">关闭</button>
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default {
  name: "DatePicker",
  props: {
    langType: {
      type: String,
      default: "zh"
    },
    date: {
      type: String,
      default: ""
    },

    isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "一", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    result: []
  }),
  watch: {
    date() {
      this.parseDate();
    },
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    getSelectDate(time) {
      for (var i = 0; i < this.result.length; i++) {
        if (time == this.result[i]) {
          return true;
        }
      }
      return false;
    },
    showPicker(e) {
      this.$emit("update:is-show",true);
      var time = new Date().getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
    },
    confirmPicker() {
      this.$emit("update:date", new Date(this.selectDate).format("yyyy-MM-dd"));
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      var tag = true;
      //已选择就取消选择
      for (var i = 0; i < this.result.length; i++) {
        if (this.result[i] == time) {
          tag = false;
          this.result.splice(i, 1);
          break;
        }
      }
      //未选择就添加日期
      if (tag) {
        this.result.push(time);
        this.result = this.result.sort(function(a, b) {
          return a - b;
        });
      }
      var list = [];
      for (var i = 0; i < this.result.length; i++) {
        if (this.result[i] > 0) {
          list.push(new Date(this.result[i]).format("yyyy-MM-dd"));
        }
      }
      if (list.length > 0) {
        this.$emit("update:date", list.join(",") + "(共" + list.length + "天)");
      } else {
        this.$emit("update:date", "");
      }

      this.$emit("picker-result", this.result);
    },
    onFullMonth() {
      this.$emit("update:date", this.year + "年" + this.month + "月份");
      this.$emit("picker-result", 30);
    },

    parseDate() {
      if (this.date) {
        var str = this.date;
        if (this.date.indexOf("(") > 0) {
          str = this.date.substring(0, this.date.indexOf("("));
        }
        if (str) {
          var list = str.split(",");
          var result = [];
          for (var i = 0; i < list.length; i++) {
            result.push(
              new Date(
                new Date(list[i]).format("yyyy-MM-dd 00:00:00")
              ).getTime()
            );
          }
          this.result = result;
        }
      }
    }
  },
  mounted() {
    this.getMonthDay();
    this.parseDate();
  }
};
</script>
<style lang="scss" scoped>
</style>

日期时间选择器

<template>
  <div style="display:inline-block">
    <span @click="showPicker">{{getLangText(label.datetimePicker)}}</span>
    <div class="date-picker-bg" v-show="isShow" @click="closePicker"></div>
    <div class="date-picker" v-show="isShow" style=" width: 260px;">
      <div class="picker-top">
        <span class="picker-arrow" @click="preYear">&lsaquo; &lsaquo;</span>
        <span class="picker-arrow" @click="preMonth">&lsaquo;</span>
        <span class="date-text">{{year}}-{{month>9?month:"0"+month}}</span>
        <span class="picker-arrow" @click="nextMonth">&rsaquo;</span>
        <span class="picker-arrow" @click="nextYear">&rsaquo;&rsaquo;</span>
      </div>
      <div class="picker-content1">
        <table>
          <thead>
            <tr>
              <th v-for="(item,idx) in weekList" :key="'week'+idx">{{getLangText(item)}}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="idx in weekNum" :key="'weekNum'+idx">
              <td
                v-for="m in 7"
                :key="'monthDay'+idx+'_'+m"
                :class="[new Date(monthList[idx-1][m-1]).getMonth()+1==month?'':'gray',selectDate==monthList[idx-1][m-1]?'active':'']"
                @click="onSelectDate(monthList[idx-1][m-1])"
                @dblclick="onConfirmDate(monthList[idx-1][m-1])"
              >{{new Date(monthList[idx-1][m-1]).getDate()}}</td>
            </tr>
          </tbody>
        </table>
        <ul class="hour-list">
          <li
            v-for="n in 24"
            :key="'hourList'+n"
            @click="onSelectHour(n-1)"
            :class="[selectHour==n-1?'active':'']"
            @dblclick="onConfirmHour(n-1)"
          >{{n-1}}:00</li>
        </ul>
      </div>
      <div class="picker-footer">
        <button @click="closePicker">{{getLangText(label.close)}}</button>
        <button @click="setNow">{{getLangText(label.today)}}</button>
        <!-- <button @click="confirmPicker">{{getLangText(label.ok)}}</button> -->
      </div>
    </div>
  </div>
</template>
<script>
Date.prototype.format = function(fmt) {
  //author: meizz
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    S: this.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};
export default {
  name: "DateTimePicker",
  props: {
    langType: {
      type: String,
      default: window.localStorage.getItem("langType")
    },
    datetime: {
      type: String,
      default: new Date().format("yyyy-MM-dd hh:00")
    },
     isShow:{
      type:Boolean,
      default:false
    }
  },
  data: () => ({

    label: {
      ok: { zh: "确定", en: "OK" },
      close: { zh: "关闭", en: "close" },
      today: { zh: "现在", en: "now" },
      datetimePicker: { zh: "日期时间选择", en: "datetimePicker" }
    },
    weekList: [
      { zh: "日", en: "Sun" },
      { zh: "一", en: "Mon" },
      { zh: "二", en: "Tue" },
      { zh: "三", en: "Wed" },
      { zh: "四", en: "Thu" },
      { zh: "五", en: "Fir" },
      { zh: "六", en: "Sat" }
    ],
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate(),

    startDay: 0,
    endDay: 0,
    weekNum: 0,
    selectDate: new Date(new Date().format("yyyy-MM-dd 00:00")).getTime(),
    monthList: [],
    selectHour: new Date().getHours()
  }),
  watch: {
    year() {
      this.getMonthDay();
    },
    month() {
      this.getMonthDay();
    }
  },
  methods: {
    getLangText(item) {
      if (item) {
        if (this.langType == "en") {
          if (item.en && item.en.length > 1) {
            return item.en.substring(0, 1).toUpperCase() + item.en.substring(1);
          } else if (item.en && item.en.length == 1) {
            return item.en.toUpperCase();
          } else {
            return "--";
          }
        } else {
          return item.zh ? item.zh : "--";
        }
      } else {
        return "--";
      }
    },
    preYear() {
      this.year = this.year - 1;
    },
    nextYear() {
      this.year = this.year + 1;
    },
    nextMonth() {
      if (this.month == 12) {
        this.year = this.year + 1;
        this.month = 1;
      } else {
        this.month++;
      }
    },
    preMonth() {
      if (this.month == 1) {
        this.year = this.year - 1;
        this.month = 12;
      } else {
        this.month--;
      }
    },
    showPicker() {
      this.$emit("update:is-show",true);

      var time = new Date(this.datetime).getTime();
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.selectDate = new Date(
        new Date(time).format("yyyy-MM-dd 00:00")
      ).getTime();
      this.selectHour = new Date(time).getHours();
    },
    onConfirmDate(time) {
      this.onSelectDate(time);
      this.confirmPicker();
    },
    onConfirmHour(n) {
      this.onSelectHour(n);
      this.confirmPicker();
    },
    closePicker() {
      this.$emit("update:is-show",false);
    },
    setNow() {
      this.year = new Date().getFullYear();
      this.month = new Date().getMonth() + 1;
      this.day = new Date().getDate();
      this.selectDate = new Date(
        new Date().format("yyyy-MM-dd 00:00")
      ).getTime();
      this.selectHour = new Date().getHours();
    },
    confirmPicker() {
      this.$emit(
        "update:datetime",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.$emit(
        "picker-result",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
      this.closePicker();
    },
    getMonthDay() {
      var monthFirst = new Date(this.year + "-" + this.month + "-01 00:00");
      var w = monthFirst.getDay();

      this.startDay = monthFirst.getTime() - w * 24 * 3600 * 1000;
      if (this.month == 12) {
        this.endDay = new Date(this.year + 1 + "-01-01 00:00").getTime() - 1000;
      } else {
        this.endDay =
          new Date(this.year + "-" + (this.month + 1) + "-01 00:00").getTime() -
          1000;
      }

      var monthDay = (this.endDay + 1000 - this.startDay) / (24 * 3600 * 1000);
      this.weekNum = Math.ceil(monthDay / 7);
      this.monthList = [];
      for (var i = 0; i < this.weekNum; i++) {
        var item = [];
        for (var j = 0; j < 7; j++) {
          item.push(
            this.startDay + i * 24 * 3600 * 1000 * 7 + j * 24 * 3600 * 1000
          );
        }
        this.monthList.push(item);
      }
    },
    onSelectHour(n) {
      this.selectHour = n;
      this.$emit(
        "update:datetime",
        new Date(this.selectDate + this.selectHour * 3600000).format(
          "yyyy-MM-dd hh:00"
        )
      );
    },
    onSelectDate(time) {
      this.selectDate = time;
      this.year = new Date(time).getFullYear();
      this.month = new Date(time).getMonth() + 1;
      this.day = new Date(time).getDate();
      this.$emit(
        "update:datetime",
        new Date(time + this.selectHour * 3600000).format("yyyy-MM-dd hh:00")
      );
    }
  },
  mounted() {
    this.getMonthDay();
  }
};
</script>
<style lang="scss" scoped>
</style>

使用Picker

<template>
<section style="padding:16px;">
  <p>date1:{{date1}}</p>
  <date-picker :date.sync="date1" :is-show.sync="showDate1"></date-picker>
   <p>date2:{{date2}}</p>
    <date-picker1 :date.sync="date2" :is-show.sync="showDate2"></date-picker1>
     <p>date3:{{date3}}</p>
    <datetime-picker :datetime.sync="date3" :is-show.sync="showDate3"></datetime-picker>
</section>
</template>

<script>
Date.prototype.format = function(fmt)
{ //author: meizz
  var o = {
    "M+" : this.getMonth()+1,                 //月份
    "d+" : this.getDate(),                    //日
    "h+" : this.getHours(),                   //小时
    "m+" : this.getMinutes(),                 //分
    "s+" : this.getSeconds(),                 //秒
    "q+" : Math.floor((this.getMonth()+3)/3), //季度
    "S"  : this.getMilliseconds()             //毫秒
  };
  if(/(y+)/.test(fmt))
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("("+ k +")").test(fmt))
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt;
}
import DateTimePicker from "./DateTimePicker";
import DatePicker from "./DatePicker";
import DatePicker1 from "./DatePicker1";
export default {
name:"PickerTest",
components:{
  'date-picker':DatePicker,
  'datetime-picker':DateTimePicker,
  'date-picker1':DatePicker1
},
data:()=>({
  showDate1:false,
  showDate2:false,
  showDate3:false,
  date1:new Date().format("yyyy-MM-dd"),
  date2:new Date().format("yyyy-MM-dd"),
  date3:new Date().format("yyyy-MM-dd hh:mm:ss"),
})
}
</script>

<style>

</style>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • ant design vue中日期选择框混合时间选择器的用法说明

    首先时间格式化用到moment方法,需要在页面中引入moment组件 import moment from 'moment' 结构代码: <a-date-picker style="width:100%" :getCalendarContainer="(triggerNode) => triggerNode.parentNode" format="YYYY-MM-DD HH:mm:ss" v-decorator="[ 'pu

  • ant design vue datepicker日期选择器中文化操作

    按照ant design vue官方说明,使用日期选择器需要在入口文件(main.js)全局设置语言: // 默认语言为 en-US,如果你需要设置其他语言,推荐在入口文件全局设置 locale import moment from 'moment'; import 'moment/locale/zh-cn'; moment.locale('zh-cn'); <a-date-picker :defaultValue="moment('2015-01-01', 'YYYY-MM-DD')&q

  • 基于Vue组件化的日期联动选择器功能的实现代码

    我们的社区前端工程用的是element组件库,后台管理系统用的是iview,组件库都很棒,但是日期.时间选择器没有那种" 年份 - 月份 -天数 " 联动选择的组件.虽然两个组件库给出的相关组件也很棒,但是有时候确实不是太好用,不太明白为什么很多组件库都抛弃了日期联动选择.因此考虑自己动手做一个. 将时间戳转换成日期格式 // timestamp 为时间戳 new Date(timestamp) //获取到时间标砖对象,如:Sun Sep 02 2018 00:00:00 GMT+08

  • Vue.js中使用iView日期选择器并设置开始时间结束时间校验功能

    具体代码如下所述: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Vue.js中使用iView日期选择器并设置开始时间结束时间校验</title> <!-- import Vue.js --> <script src="//vuejs.org/js/vue.min.js"></script

  • Vue日期时间选择器组件使用方法详解

    本文实例为大家分享了Vue日期时间选择器组件的具体代码,供大家参考,具体内容如下 1.效果图如下 单选日期选择器 多选日期选择器 日期时间选择器 2.准备 Date原型格式化工具方法 Date.prototype.format = function(fmt) { //author: meizz var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": thi

  • vue加载天气组件使用方法详解

    本文实例为大家分享了vue加载天气组件的使用方法,供大家参考,具体内容如下 首先我们进入中国天气网生成一段代码 根据需要设置天气样式 复制并修改生成的这段代码到vue中 将script引入 修改为vue的动态引入方法 <template> <div id="weater"> <div id="weather-view-he" ref="weather"></div> <remote-scrip

  • Vue自嵌套树组件使用方法详解

    本文实例为大家分享了Vue自嵌套树组件的使用方法,供大家参考,具体内容如下 效果图 注意事项 组件自嵌套,定义名称时就定义为组件名 单选和多选用户时,以最顶级父组件的属性为准,由于组件内不能同步修改prop,故采用data注册另一个同类型数值用于接收组件内改变,并使用update,同步更新到prop上 展开组件才开始加载用户列表 <template> <ul v-show="isShow" ref="user-tree"> <li v-

  • Vue跑马灯marquee组件使用方法详解

    本文实例为大家分享了Vue跑马灯marquee组件的具体代码,供大家参考,具体内容如下 一.实现效果 二.实现过程 前言:最开始用间隔器方案制作了一个跑马灯,但是放在移动端中会出现严重的掉帧卡顿现象,于是整理思路后采用transition方案制作一个从右到左的动画处理问题 思路整理: 1. 过渡是需要设定时间的,但是跑马灯中的文本可能是长短不一的 解决方案:根据文本的总宽度(即文本总长)设定过渡时间,假设文本宽度500px,我们将其除以50,即过渡时间为10s 原生js表示如下: const t

  • Vue.js标签页组件使用方法详解

    本文实例为大家分享了Vue.js标签页组件使用的具体代码,供大家参考,具体内容如下 效果 入口页 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0&q

  • Vue.js数字输入框组件使用方法详解

    本文实例为大家分享了Vue.js数字输入框组件的具体实现代码,供大家参考,具体内容如下 效果 入口页 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0

  • vue+elementUI面包屑组件封装方法详解

    本文实例为大家分享了vue+elementUI面包屑组件封装的具体代码,供大家参考,具体内容如下 一.选择用哪种样式 二.在组件文件夹下创建组件 三.在Bread.vue复制如下代码 <template>   <!-- 面包屑 -->   <div class="bread">  <el-breadcrumb separator-class="el-icon-arrow-right">  <el-breadcru

  • vue使用keep-alive进行组件缓存方法详解(组件不缓存问题解决)

    目录 一.使用场景 二. 认识下keep-alive 三.在组件中应用 四.解决组件不缓存问题 五.keep-alive配合router使用 总结 一.使用场景 在vue开发过程中(单页面),有一些需求需要我们把页面状态保存下来.在切换页面时,页面不会进行重新加载. 一般情况下,如果不做特殊处理,会重新执行created 和 mounted生命周期,从而重新加载页面,默认就显示到第一页去了,就很烦. (我的问题是,使用keep-alive了,但组件仍然不缓存,下面会解决) 二. 认识下keep-

  • Vue使用Swiper封装轮播图组件的方法详解

    目录 Swiper 为什么要封装组件 开始封装 1.下载安装Swiper 2.引入css样式文件 3.引入js文件 4.把官网使用方法中的HTML结构复制粘贴过来 5.初始化Swiper 自定义效果 完整代码 效果展示 Swiper Swiper是一个很常用的用于实现各种滑动效果的插件,PC端和移动端都能很好的适配. 官网地址:www.swiper.com.cn/ 目前最新版本是Swiper7,但众所周知最新版本通常不稳定,所以这里使用Swiper6来封装. Swiper各版本区别: 为什么要封

  • 使用Vue开发动态刷新Echarts组件的教程详解

    需求背景:dashboard作为目前企业中后台产品的"门面",如何更加实时.高效.炫酷的对统计数据进行展示,是值得前端开发工程师和UI设计师共同思考的一个问题.今天就从0开始,封装一个动态渲染数据的Echarts折线图组件,抛砖引玉,一起来思考更多有意思的组件. 准备工作 项目结构搭建 因为生产需要(其实是懒),所以本教程使用了 ==vue-cli==进行了项目的基础结构搭建. npm install -g vue-cli vue init webpack vue-charts cd

随机推荐