Vue+Vant 基于DatetimePicker进行二次开发,实现yyyyMMdd hh:mm:ss时间选择

Vue+Vant 基于DatetimePicker进行二次开发,实现yyyyMMdd hh:mm:ss时间选择

1.效果图

在这里插入图片描述

2.前提

vue引入Vant:

vue2.0
npm i vant -S

vue3.0
npm i vant@next -S

main.js 引入Vant

import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);

3.项目结构

在这里插入图片描述

4.index.vue

<template>
  <div class="time-box">
    <span>开始时间:</span>
    <TimeSelection
    clearValue
    placeholderText="开始时间"
    :inputWidth="230"
    :inputHeight="35"
    :types="types" 
    :nowShowTime="startTime" 
    @change="getTime"
    />
  </div>
</template>
<script>
import TimeSelection from './children/timeSelection.vue'
export default {
  components:{TimeSelection},
  data(){
    return{
      startTime:null,
      types:'date-seconds', //date-seconds(年月日 时分秒)、date-minutes(年月日 时分)、
                            //date-hour(年月日 时)、date(年月日)、year-month(年月)、year(年)
    }
  },
  methods:{
    getTime(val) {
      this.startTime = val
    }
  }
}
</script>
<style scoped>
.time-box{
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
}
</style>

5.timeSelection.vue

<template>
<div>
  <div class="d-input"
  :style="{'width':inputWidth+'px','height':inputHeight+'px'}"
  >
    <input 
    class="input-left"
    :style="{'width':(clearValue&&seletTime!='')?inputWidthLeft:inputWidth,'height':'100%'}"
    :placeholder="placeholderText" 
    readonly="readonly"
    v-model="seletTime" 
    @click="show"
    />
    <van-icon v-if="(clearValue&&seletTime!='')" name="close" size="15"
    @click="deleteData"
    />
  </div>
  <van-popup
    v-model="isShowTime" position="bottom" :style="{ height: '40%' }">
    <van-datetime-picker
      v-if="isShowYMD"
      v-model="defaultCurrentDate"
      :min-date="minSelectDate"
      :max-date="maxSelectDate"
      :type="types=='date'?'date':
      types=='year-month'?'year-month':
      types=='year'?'year':
      'date'"
      :title="title1"
      @confirm="confirmYMD"
      @cancel="cancelYMD"
    />
    <van-picker
      v-if="isShowHMS"
      show-toolbar
      :title="title2"
      :columns="
      types=='date-seconds'?hourMinuteSecond:
      types=='date-minutes'?hourMinute:
      types=='date-hour'?hour:
      hourMinuteSecond"
      @confirm="confirmHMS"
      @cancel="cancelYMD"
    />
    <van-picker
      v-if="isShowYear"
      show-toolbar
      :title="title3"
      :columns="year"
      @confirm="confirmYear"
      @cancel="cancelYear"
    />
  </van-popup>
</div>
  
</template>

<script>
import util from './util'
export default {
  props:{
    minDate:{
      type:Date,
      default:function(){
        return new Date(2000, 0, 1);
      },
    },
    maxDate:{
      type:Date,
      default:function(){
        return new Date(util.formatDate(new Date(),9));
      },
    },
    currentDate:{
      type:Date,
      default:function(){
        return new Date();
      },
    },
    nowShowTime:{
      type:String,
      default:''
    },
    types:{
      type:String,
      default:"date-seconds"
    },
    inputWidth:{
      type:Number,
      default:200
    },
    inputHeight:{
      type:Number,
      default:40
    },
    placeholderText:{
      type:String,
      default:"时间选择"
    },
    clearValue:{
      type:Boolean,
      default:false,
    },
  },
  data(){
    return{
      inputWidthLeft:'',

      isShowTime:false,
      isShowYMD:false,
      isShowHMS:false,
      isShowYear:false,

      title1:'选择年月日',
      title2:'选择时分秒',
      title3:'选择年',

      minSelectDate:new Date(2000, 0, 1),
      maxSelectDate:new Date(util.formatDate(new Date(),9)),
      defaultCurrentDate:new Date(),

      selectYMD:null,//选择的年月日
      selectHMS:null,//选择的时分秒
      seletTime:'',//最终选择的时间

      hourMinuteSecond:[
         // 第一列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23'],
          defaultIndex:0,
        },
        // 第二列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59'],
          defaultIndex: 0,
        },
        //第三列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59'],
          defaultIndex: 0,
        },
      ],//时分秒数据
      hourMinute:[
        // 第一列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23'],
          defaultIndex:0,
        },
        // 第二列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59'],
          defaultIndex: 0,
        },
      ],//时分数据
      hour:[
        // 第一列
        {
          values: ['00', '01', '02', '03', '04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','21','22','23'],
          defaultIndex:0,
        },
      ],//小时数据
      year:[
        {
          values:[],
          defaultIndex:0
        }
      ]
    }
  },
  watch:{
    minDate:function(val){
      this.minSelectDate = val
    },
    maxDate:function(val) {
      this.maxSelectDate = val
    },
    currentDate:function(val){
      this.defaultCurrentDate = val
    },
    nowShowTime:function(val){
      if(!util.isEmpty(val)){
        this.seletTime = val
        this.defaultCurrentDate = new Date(val)
      }else{
        this.seletTime = ''
        this.defaultCurrentDate = new Date()
      }
    },
    inputWidth:function(val){
      if(!util.isEmpty(val)){
        if(this.inputWidth){
          this.inputWidthLeft = (val-30)+'px'
        }else{
          this.inputWidthLeft = '120px'
        }
      }else{
        this.inputWidthLeft = '120px'
      }
    },
  },
  mounted(){
    if(!util.isEmpty(this.nowShowTime)){
      this.seletTime = this.nowShowTime
      this.defaultCurrentDate = new Date(this.seletTime)
    }else{
      this.seletTime = ''
      this.defaultCurrentDate = new Date()
    }

    this.setYearList()
    if(!util.isEmpty(this.inputWidth)){
      this.inputWidthLeft = (this.inputWidth-30)+'px'
    }else{
      this.inputWidthLeft = '120px'
    }
  },
  methods:{
    //是否显示时间选择弹窗
    show(){
      this.isShowTime = true
      if(this.types == 'year') {
        this.isShowYMD = false
        this.isShowHMS = false
        this.isShowYear = true
        this.setYear()
        this.title1 = '选择年月日'
        this.title2 = '选择时分秒'
      }else{
        this.isShowYMD = true
        this.isShowHMS = false
        this.isShowYear = false
        if(this.types == 'date-seconds'){ //年月日 时分秒
          this.title1 = '选择年月日'
          this.title2 = '选择时分秒'
        }else if(this.types == 'date-minutes'){ //年月日 时分
          this.title1 = '选择年月日'
          this.title2 = '选择时分'
        }else if(this.types == 'date-hour'){ //年月日 时
          this.title1 = '选择年月日'
          this.title2 = '选择小时'
        }else if(this.types == 'date'){ //年月日
          this.title1 = '选择年月日'
          this.title2 = '选择时分秒'
        }else if(this.types == 'year-month'){ //年月
          this.title1 = '选择年月'
          this.title2 = '选择时分秒'
        }
      }
    },
    

    //时分秒设置
    setHMS(){
      this.hourMinuteSecond[0].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[0]==item){
						this.hourMinuteSecond[0].defaultIndex = Number(item)
				}
			})
			this.hourMinuteSecond[1].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[1]==item){
						this.hourMinuteSecond[1].defaultIndex = Number(item)
				}
			})
			this.hourMinuteSecond[2].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[2]==item){
						this.hourMinuteSecond[2].defaultIndex = Number(item)
				}
			})
    },
    //设置时分
    setHM(){
      this.hourMinute[0].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[0]==item){
						this.hourMinute[0].defaultIndex = Number(item)
				}
			})
			this.hourMinute[1].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[1]==item){
						this.hourMinute[1].defaultIndex = Number(item)
				}
			})
    },
    //设置时
    setH(){
      this.hour[0].values.forEach(item=>{
				if(util.formatDate(new Date(),8)[0]==item){
					this.hour[0].defaultIndex = Number(item)
				}
			})
    },


    //设置年
    setYear(){
      this.year[0].values.forEach(item=>{
				if(util.formatDate(new Date(),9)[0]==item){
					this.year[0].defaultIndex = Number(item)
				}
			})
    },
    //确认选择年
    confirmYear(value){
      this.seletTime = value[0]
      this.$emit('change',this.seletTime)
      this.isShowTime = false
    },
    //取消选择年
    cancelYear(){
      this.isShowYear = false
    },
    //设置年选择的列表
    setYearList(){
      let numberArr = []
      let nowYear = new Date().getFullYear()
      for(let j=2010;j<=nowYear;j++){
        numberArr.push(String(j))
      }
      this.year[0].values = numberArr
    },


    //确认选择年月日数据
    confirmYMD(value){
      this.isShowYMD = false
      if(this.types == 'date-seconds'){ //年月日 时分秒
        this.selectYMD = util.formatDate(value,1)
        this.isShowHMS = true
        this.setHMS()
      }else if(this.types == 'date-minutes'){ //年月日 时分
        this.selectYMD = util.formatDate(value,1)
        this.isShowHMS = true
        this.setHM()
      }else if(this.types == 'date-hour'){ //年月日 时
        this.selectYMD = util.formatDate(value,1)
        this.isShowHMS = true
        this.setH()
      }else if(this.types == 'date'){ //年月日
        this.seletTime = util.formatDate(value,1)
        this.$emit('change',this.seletTime)
        this.isShowTime = false
        this.isShowHMS = false
      }else if(this.types == 'year-month'){ //年月
        this.seletTime = util.formatDate(value,7)
        this.$emit('change',this.seletTime)
        this.isShowTime = false
        this.isShowHMS = false
      }
    },
    //确定选择时分秒
    confirmHMS(value){
      this.selectHMS = value
      if(this.types == 'date-seconds'){
        this.seletTime = this.selectYMD + ' '+this.selectHMS[0]+':'+this.selectHMS[1]+':'+this.selectHMS[2]
      }else if(this.types == 'date-minutes'){
        this.seletTime = this.selectYMD + ' '+this.selectHMS[0]+':'+this.selectHMS[1]
      }else if(this.types == 'date-hour'){
        this.seletTime = this.selectYMD + ' '+this.selectHMS[0]+':00'
      }
      this.$emit('change',this.seletTime)
      this.isShowTime = false
    },
    //取消时间选择
    cancelYMD(){
      this.isShowTime = false
    },

    //删除选择的时间
    deleteData(){
      this.seletTime = ''
      this.$emit('change','')
    },
  }
};
</script>

<style scoped>
.d-input{
  box-sizing: border-box;
  border-radius: 5px;
  border: 1px solid #ddd;
  align-items: center;
}
.input-left{
  overflow: auto;
  word-break: keep-all;
  padding: 0 5px;
  box-sizing: border-box;
}
input{
  background:none;  
	outline:none;  
	border:none;
}
</style>

6.util.js

//时间格式化
function formatDate(date, type = 1) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var weekday = date.getDate();
    var hour = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    //月,日 ,时,分,秒,没有拼接0
    let months = month
    let weekdays = weekday
    let hours = hour
    let minutess = minutes
    let secondss = seconds

    if (month < 10) {
        month = "0" + month;
    }
    if (weekday < 10) {
        weekday = "0" + weekday;
    }
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }

    if (type == 1) {
        return (year + "-" + month + "-" + weekday);
    } else if (type == 2) {
        return (hour + ":" + minutes + ":" + seconds);
    } else if (type == 3) {
        return (year + "-" + month + "-" + weekday + ' ' + hour + ":" + minutes + ":" + seconds)
    } else if (type == 4) {
        return year + "/" + months + "/" + weekdays + " " + hours + ":" + minutess + ":" + secondss;
    } else if (type == 5) {
        return [hour, minutes, seconds]
    } else if (type == 6) {
        return (year + "年" + month + "月" + weekday + '日');
    } else if (type == 7) {
        return (year + "-" + month);
    } else if (type == 8) {
        return ([hour, minutes, seconds])
    } else if (type == 9) {
        return ([year, months, weekdays])
    } else if (type == 10) {
        return (year + "-" + month + "-" + weekday + ' ' + hour + ":00")
    }
}

//非空判断
function isEmpty(str) {
    if (str == null || str == "") {
        return true;
    }
    return false;
}

export default {
    formatDate,
    isEmpty
}

7.注意

如引用本文内容,请标明出处。
有问题可留言

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值