基於Vue組件化的日期聯動選擇器功能的實現代碼

来源:https://www.cnblogs.com/qdgc/archive/2018/12/09/10091732.html
-Advertisement-
Play Games

我們的社區前端工程用的是element組件庫,後臺管理系統用的是iview,組件庫都很棒,但是日期、時間選擇器沒有那種“ 年份 - 月份 -天數 ” 聯動選擇的組件。雖然兩個組件庫給出的相關組件也很棒,但是有時候確實不是太好用,不太明白為什麼很多組件庫都拋棄了日期聯動選擇。因此考慮自己動手做一個。 ...


我們的社區前端工程用的是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>//歡迎加入前端全棧開發交流圈一起學習交流:864305860
  </el-select>//面向1-3年前端人員
  <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
 };//歡迎加入前端全棧開發交流圈一起學習交流:864305860
 },
 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();
 },//歡迎加入前端全棧開發交流圈一起學習交流:864305860
 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(); //發送結果至父組件或其他地方
  },//歡迎加入前端全棧開發交流圈一起學習交流:864305860
  deep: true
 }//面向1-3年前端人員
}//幫助突破技術瓶頸,提升思維能力

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();
 } //歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
 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 = "";
  }//歡迎加入前端全棧開發交流圈一起吹水聊天學習交流:864305860
 }//面向1-3年前端人員
}//幫助突破技術瓶頸,提升思維能力

結語

感謝您的觀看,如有不足之處,歡迎批評指正。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 文章鏈接: "https://mp.weixin.qq.com/s/1gkMtLu0BTXOUOj6isDjUw" 日常android開發過程中,會遇到編輯框輸入內容彈出軟鍵盤,往往會出現鍵盤遮擋內容,或者出現頁面整體上移的,或多或少在體驗上都不是很優雅,今天提供個方法是自行控制頁面上移距離,竟可能 ...
  • 用react也有段時間了, 是時候看看人家源碼了. 看源碼之前看到官方文檔有這麼篇文章介紹其代碼結構了, 為了看源碼能順利些, 遂決定將其翻譯來看看, 小弟英語也是半瓢水, 好多單詞得查詞典, 不當之處請批評. 直接從字面翻譯的, 後面看源碼後可能會在再修改下. ...
  • 本文會透過以下幾個段落,讓各位一步一步學習如何寫一個自已的Node.js Module並且發佈到npm package上 Node.js Module 結構 我們先建立一個 NodeModuleDemo 的資料夾 ,接下來利用 npm init 進行初始化 (這裡不用特別設置,一路按 Enter 到 ...
  • 執行環境是JavaScrpt 最重要的概念之一,執行環境定義了變數或函數有權訪問的其它數據,決定了它們各自的行為。每個執行環境都有一個與之關聯的變數對象,或者說一個執行環境就是一個對象。環境中定義的所有變數和函數都保存在這個對象中。雖然我們編寫的代碼無法訪問這個對象,但解析器在處理數據時會在後臺使用 ...
  • 編碼 現在我們要做一個稍微複雜的東西,如下HTML,有一堆Select用於選擇日期和時間,在選擇後,實時在 id 為 result-wrapper 的 p 標簽中顯示所選時間和當前時間的差值。 使用上方的HTML結構(可以根據需要自行微調)為基礎編寫JavaScript代碼 當變更任何一個selec ...
  • 1. 受控組件:組件處於受控制狀態,不可更改輸入框內的值。 2. 什麼情況下會讓組件變成受控組件? - 文本框設置了value屬性的時候 - 單選框或多選框設置了checked屬性的時候。 3. 如何解決? - 使用state設置值 - 綁定onChange事件 - 在事件處理方法中獲取組件的值並更 ...
  • 前言 在我一開始學習java web的時候,對JS就一直抱著一種只是簡單用用的心態,於是並沒有一步一步地去學習,當時認為用法與java類似,但是在實際web項目中使用時卻比較麻煩,便直接粗略瞭解後開始使用jQuery。但現如今,前端發展迅速,js語法方便也有了相當大的改善,並且伴隨著node.js的 ...
  • 本文主要介紹了VueJS 組件參數名命名與組件屬性轉化問題,具有一定的參考價值,對此有需要的朋友可以參考學習下。如有不足之處,歡迎批評指正。 HTML 特性是不區分大小寫的。所以,當使用的不是字元串模版,camelCased (駝峰式) 命名的 prop 需要轉換為相對應的 kebab-case ( ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...