Vant-UI之日期选择器封装(日期选择)

1,050 阅读1分钟

写在前面

H5的项目,是利用Vant-ui-2版本做的,由于Calendar 日历组件的交互不能满足需求且使用相对麻烦,于是就基于DatetimePicker做了一次封装,满足业务需求。

实现逻辑

  • 确定组件需要的参数,统一组件的入口和出口doInit()方法和cancel()方法
  • 定义组件交互的逻辑(日期选择、起止时间要符合逻辑、选中的时间可以是YYYY-MM-DDYYYY-MM-DD hh:mm:ss时间对象
  • 参数:最小时间、最大时间、当前默认时间

代码部分

<template>
  <van-popup v-model="isShow" position="bottom">
    <van-datetime-picker
      :key="dateKey"
      v-model="currentDate"
      type="date"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="confirm"
      @cancel="cancel"
    />
  </van-popup>
</template>

<script>
// 组件 - 
import { formatDate, formatDateFull } from '../utils';

export default {
  name: 'DateLine',
  data() {
    return {
      dateKey: 1,
      isShow: false,
      minDate: '',
      maxDate: '',
      currentDate: ''
    };
  },
  methods: {
    doInit({ minDate, maxDate, currentDate }) {
      this.dateKey++;// 每次进入强制刷新
      if (!minDate) {
        this.minDate = new Date(2010, 0, 1);
      } else {
        this.minDate = minDate;
      }

      if (!maxDate) {
        this.maxDate = new Date(2050, 0, 1);
      } else {
        this.maxDate = maxDate;
      }

      if (!currentDate) {
        this.currentDate = new Date();
      } else if (currentDate.length >= 10) {
        const year = currentDate.substring(0, 4);
        const month = currentDate.substring(5, 7) - 1;
        const day = currentDate.substring(8, 10);
        this.currentDate = new Date(year, month, day);
      } else {
        this.currentDate = currentDate;
      }

      this.isShow = true;
    },
    confirm() {
      let currentDate = this.currentDate;
      this.$emit('confirm', {
        date: currentDate,
        dateStr: formatDate(currentDate, '-'),
        dateStrFull: formatDateFull(currentDate, '-')
      });
      this.cancel();
    },
    cancel() {
      this.isShow = false;
    }
  }
};
</script>
/**
 * 格式化日期
 *
 * @param date 日期对象
 * @param str 日期连接符:默认/
 * @return {string}
 */
export const formatDate = (date = new Date(), str = '/') => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  return [year, month, day].map(formatNumber).join(str);
};
/**
 * 格式化时间
 *
 * @param date
 * @returns {string}
 */
export const formatTime = (date = new Date()) => {
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return [hour, minute, second].map(formatNumber).join(':');
};
/**
 * 格式化日期和时间
 *
 * @param date
 * @param str
 * @returns {string}
 */
export const formatDateFull = (date = new Date(), str = '/') => {
  return formatDate(date, str) + ' ' + formatTime();
};

使用

  • 使用$refs调用组件的doInit方法
  • minDate默认2010-1-1,maxDate默认2050-1-1
  • 确认后传出一个对象包含三种格式的时间

效果

下载.gif

写到最后

如有不足之处,还请各位大佬指正,后续持续优化!