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


Posted in Javascript onNovember 30, 2018

我们的社区前端工程用的是element组件库,后台管理系统用的是iview,组件库都很棒,但是日期、时间选择器没有那种“ 年份 - 月份 -天数 ” 联动选择的组件。虽然两个组件库给出的相关组件也很棒,但是有时候确实不是太好用,不太明白为什么很多组件库都抛弃了日期联动选择。因此考虑自己动手做一个。

将时间戳转换成日期格式

// timestamp 为时间戳
new Date(timestamp)
//获取到时间标砖对象,如:Sun Sep 02 2018 00:00:00 GMT+0800 (中国标准时间)
/*
 获取年: new Date(timestamp).getFullYear()
 获取月: new Date(timestamp).getMonth() + 1
 获取日: new Date(timestamp).getDate() 
 获取星期几: new Date(timestamp).getDay() 
*/

将日期格式(yyyy-mm-dd)转换成时间戳

//三种形式
 new Date('2018-9-2').getTime()
 new Date('2018-9-2').valueOf()
 Date.parse(new Date('2018-9-2'))

IE下的兼容问题

注意: 上述代码在IE10下(至少包括IE10)是没法或得到标准时间value的,因为 2018-9-2 并不是标准的日期格式(标准的是 2018-09-02),而至少 chrome 内核为我们做了容错处理(估计火狐也兼容)。因此,必须得做严格的日期字符串整合操作,万不可偷懒

基于Vue组件化的日期联机选择器

该日期选择组件要达到的目的如下:

(1) 当前填入的日期不论完整或缺省,都要向父组件传值(缺省传''),因为父组件要根据获取的日期值做相关处理(如限制提交等操作等);
(2) 具体天数要做自适应,即大月31天、小月30天、2月平年28天、闰年29天;
(3) 如先选择天数为31号(或30号),再选择月数,如当前选择月数不含已选天数,则清空天数;
(4) 如父组件有时间戳传入,则要将时间显示出来供组件修改。

实现代码(使用的是基于Vue + element组件库)

 

<template>
 <div class="date-pickers">
  <el-select 
  class="year select"
  v-model="currentDate.year"
  @change='judgeDay'
  placeholder="年">
   <el-option
   v-for="item in years"
   :key="item"
   :label="item"
   :value="item">
   </el-option>
  </el-select>
  <el-select 
  class="month select"
  v-model="currentDate.month" 
  @change='judgeDay'
  placeholder="月">
   <el-option
   v-for="item in months"
   :key="item"
   :label="String(item).length==1?String('0'+item):String(item)"
   :value="item">
   </el-option>
  </el-select>
  <el-select 
  class="day select"
  :class="{'error':hasError}"
  v-model="currentDate.day" 
  placeholder="日">
   <el-option
   v-for="item in days"
   :key="item"
   :label="String(item).length==1?String('0'+item):String(item)"
   :value="item">
   </el-option>
  </el-select>
 </div>
</template>
<script>
export default {
 props: {
 sourceDate: {
  type: [String, Number]
 }
 },
 name: "date-pickers",
 data() {
 return {
  currentDate: {
  year: "",
  month: "",
  day: ""
  },
  maxYear: new Date().getFullYear(),
  minYear: 1910,
  years: [],
  months: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
  normalMaxDays: 31,
  days: [],
  hasError: false
 };
 },
 watch: {
 sourceDate() {
  if (this.sourceDate) {
  this.currentDate = this.timestampToTime(this.sourceDate);
  }
 },
 normalMaxDays() {
  this.getFullDays();
  if (this.currentDate.year && this.currentDate.day > this.normalMaxDays) {
  this.currentDate.day = "";
  }
 },
 currentDate: {
  handler(newValue, oldValue) {
  this.judgeDay();
  if (newValue.year && newValue.month && newValue.day) {
   this.hasError = false;
  } else {
   this.hasError = true;
  }
  this.emitDate();
  },
  deep: true
 }
 },
 created() {
 this.getFullYears();
 this.getFullDays();
 },
 methods: {
 emitDate() {
  let timestamp; //暂默认传给父组件时间戳形式
  if ( this.currentDate.year && this.currentDate.month && this.currentDate.day) {
   let month = this.currentDate.month < 10 ? ('0'+ this.currentDate.month):this.currentDate.month;
   let day = this.currentDate.day < 10 ? ('0'+ this.currentDate.day):this.currentDate.day;
   let dateStr = this.currentDate.year + "-" + month + "-" + day;
   timestamp = new Date(dateStr).getTime();
  } 
  else {
   timestamp = "";
  }
  this.$emit("dateSelected", timestamp);
 },
 timestampToTime(timestamp) {
  let dateObject = {};
  if (typeof timestamp == "number") {
  dateObject.year = new Date(timestamp).getFullYear();
  dateObject.month = new Date(timestamp).getMonth() + 1;
  dateObject.day = new Date(timestamp).getDate();
  return dateObject;
  }
 },
 getFullYears() {
  for (let i = this.minYear; i <= this.maxYear; i++) {
  this.years.push(i);
  }
 },
 getFullDays() {
  this.days = [];
  for (let i = 1; i <= this.normalMaxDays; i++) {
  this.days.push(i);
  }
 },
 judgeDay() {
  if ([4, 6, 9, 11].indexOf(this.currentDate.month) !== -1) {
  this.normalMaxDays = 30; //小月30天
  if (this.currentDate.day && this.currentDate.day == 31) {
   this.currentDate.day = "";
  }
  } else if (this.currentDate.month == 2) {
  if (this.currentDate.year) {
   if (
   (this.currentDate.year % 4 == 0 &&
    this.currentDate.year % 100 != 0) ||
   this.currentDate.year % 400 == 0
   ) {
   this.normalMaxDays = 29; //闰年2月29天
   } else {
   this.normalMaxDays = 28; //闰年平年28天
   }
  } 
  else {
   this.normalMaxDays = 28;//闰年平年28天
  }
  } 
  else {
  this.normalMaxDays = 31;//大月31天
  }
 }
 }
};
</script>
<style lang="less">
.date-pickers {
 .select {
 margin-right: 10px;
 width: 80px;
 text-align: center;
 }
 .year {
 width: 100px;
 }
 .error {
 .el-input__inner {
  border: 1px solid #f1403c;
  border-radius: 4px;
 }
 }
}
</style>

代码解析

默认天数(normalMaxDays)为31天,最小年份1910,最大年份为当前年(因为我的业务场景是填写生日,大家这些都可以自己调)并在created 钩子中先初始化年份和天数。

监听当前日期(currentDate)

核心是监听每一次日期的改变,并修正normalMaxDays,这里对currentDate进行深监听,同时发送到父组件,监听过程:

watch: {
 currentDate: {
  handler(newValue, oldValue) {
  this.judgeDay(); //更新当前天数
  this.emitDate(); //发送结果至父组件或其他地方
  },
  deep: true
 }
}

judgeDay方法:

judgeDay() {
 if ([4, 6, 9, 11].indexOf(this.currentDate.month) !== -1) {
 this.normalMaxDays = 30; //小月30天
 if (this.currentDate.day && this.currentDate.day == 31) {
  this.currentDate.day = ""; 
 }
 } else if (this.currentDate.month == 2) {
 if (this.currentDate.year) {
  if (
  (this.currentDate.year % 4 == 0 &&
   this.currentDate.year % 100 != 0) ||
  this.currentDate.year % 400 == 0
  ) {
  this.normalMaxDays = 29; //闰年2月29天
  } else {
  this.normalMaxDays = 28; //平年2月28天
  }
 } else {
  this.normalMaxDays = 28; //平年2月28天
 }
 } else {
 this.normalMaxDays = 31; //大月31天
 }
}

最开始的时候我用的 includes判断当前月是否是小月:

if([4, 6, 9, 11].includes(this.currentDate.month))

也是缺乏经验,最后测出来includes 在IE10不支持,因此改用普通的indexOf()。

emitDate:
emitDate() {
 let timestamp; //暂默认传给父组件时间戳形式
 if ( this.currentDate.year && this.currentDate.month && this.currentDate.day) {
  let month = this.currentDate.month < 10 ? ('0'+ this.currentDate.month):this.currentDate.month;
  let day = this.currentDate.day < 10 ? ('0'+ this.currentDate.day):this.currentDate.day;
  let dateStr = this.currentDate.year + "-" + month + "-" + day;
  timestamp = new Date(dateStr).getTime();
 } 
 else {
  timestamp = "";
 }
 this.$emit("dateSelected", timestamp);//发送给父组件相关结果
},

这里需要注意的,最开始并没有做上述标准日期格式处理,因为chrome做了适当容错,但是在IE10就不行了,所以最好要做这种处理。

normalMaxDays改变后必须重新获取天数,并依情况清空当前选择天数:

watch: {
 normalMaxDays() {
  this.getFullDays();
  if (this.currentDate.year && this.currentDate.day > this.normalMaxDays) {
  this.currentDate.day = "";
  }
 }
}

最终效果

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

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

总结

以上所述是小编给大家介绍的基于Vue组件化的日期联动选择器功能的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Javascript 相关文章推荐
写了一个layout,拖动条连贯,内容区可为iframe
Aug 19 Javascript
Js动态创建div
Sep 25 Javascript
JavaScript版DateAdd和DateDiff函数代码
Mar 01 Javascript
jQuery中extend函数详解
Feb 13 Javascript
JavaScript中Date对象的常用方法示例
Oct 24 Javascript
实现高性能JavaScript之执行与加载
Jan 30 Javascript
angular route中使用resolve在uglify压缩后问题解决
Sep 21 Javascript
JS实现异步上传压缩图片
Apr 22 Javascript
vuex学习之Actions的用法详解
Aug 29 Javascript
Vue单页及多页应用全局配置404页面实践记录
May 22 Javascript
mock.js实现模拟生成假数据功能示例
Jan 15 Javascript
JavaScript获取页面元素的常用方法详解
Sep 28 Javascript
vue拖拽排序插件vuedraggable使用方法详解
Aug 21 #Javascript
JS实现图片拖拽交换效果
Nov 30 #Javascript
Vue+Webpack完美整合富文本编辑器TinyMce的方法
Nov 30 #Javascript
jQuery实现网页拼图游戏
Apr 22 #jQuery
vue 双向数据绑定的实现学习之监听器的实现方法
Nov 30 #Javascript
基于jquery实现九宫格拼图小游戏
Nov 30 #jQuery
微信小程序canvas.drawImage完全显示图片问题的解决
Nov 30 #Javascript
You might like
PHP IF ELSE简化/三元一次式的使用
2011/08/22 PHP
如何用php生成扭曲及旋转的验证码图片
2013/06/07 PHP
提高PHP性能的编码技巧以及性能优化详细解析
2013/08/24 PHP
php实现字符串反转输出的方法
2015/03/14 PHP
推荐十款免费 WordPress 插件
2015/03/24 PHP
微信API接口大全
2015/04/15 PHP
在php中设置session用memcache来存储的方法总结
2016/01/14 PHP
php中文语义分析实现方法示例
2019/09/28 PHP
JS网络游戏-(模拟城市webgame)提供的一些例子下载
2007/10/14 Javascript
javascript 中that的含义示例介绍
2014/05/14 Javascript
JavaScript定义类和对象的方法
2014/11/26 Javascript
JS+CSS实现经典的左侧竖向滑动菜单效果
2015/09/23 Javascript
vue-cli的webpack模板项目配置文件分析
2017/04/01 Javascript
angularjs手动识别字符串中的换行符方法
2018/10/02 Javascript
JavaScript检查数据中是否存在相同的元素(两种方法)
2018/10/07 Javascript
JavaScript代码调试方法实例小结
2019/01/05 Javascript
React优化子组件render的使用
2019/05/12 Javascript
JS实现点击生成UUID的方法完整实例【基于jQuery】
2019/06/12 jQuery
Python编程判断一个正整数是否为素数的方法
2017/04/14 Python
Python实现模拟分割大文件及多线程处理的方法
2017/10/10 Python
Pyinstaller将py打包成exe的实例
2018/03/31 Python
对python 多线程中的守护线程与join的用法详解
2019/02/18 Python
pyqt 实现QlineEdit 输入密码显示成圆点的方法
2019/06/24 Python
Python获取好友地区分布及好友性别分布情况代码详解
2019/07/10 Python
python3中替换python2中cmp函数的实现
2019/08/20 Python
python中通过selenium简单操作及元素定位知识点总结
2019/09/10 Python
Pandas-Cookbook 时间戳处理方式
2019/12/07 Python
Python 序列化和反序列化库 MarshMallow 的用法实例代码
2020/02/25 Python
python判断两个序列的成员是否一样的实例代码
2020/03/01 Python
Bowflex美国官方网站:高级家庭健身器材
2017/12/22 全球购物
美国家居装饰购物网站:Amanda Lindroth
2020/03/25 全球购物
初婚未育证明样本
2014/10/24 职场文书
检讨书范文大全
2015/05/07 职场文书
2015年幼儿园中班下学期工作总结
2015/05/22 职场文书
2016读书月活动心得体会
2016/01/14 职场文书
承诺书应该怎么写?
2019/09/10 职场文书