search
HomeWeb Front-endJS TutorialHow to use datepicker

This time I will show you how to use datepicker, what are the precautions when using datepicker, the following is a practical case, let's take a look.

Preface

Writing plug-ins is very interesting and very challenging, because many details can be discovered in the process. In the process of front-end development, jQuery is undoubtedly an important milestone. Around this excellent project, many excellent plug-ins have emerged that can be used directly, greatly saving developers time. The most important role of jQuery is cross-browser. Although the browser market is not perfect now, it is far from as miserable as it used to be. The idea of ​​data-driven views is very popular. People are starting to use front-end frameworks to replace jQuery. I personally prefer Vue. js, so I want to try writing a component using Vue.js.

In order to publish it to npm, I changed the name of the project address, but the internal code has not been changed, and the usage is more convenient than before.

GitHub address: Here

Functions & Expectations

This datepicker currently only implements some common functions:

  1. Select time (This is a bit redundant)

  2. Maximum/minimum time limit

  3. Chinese/English switching (actually, only the week and month need to be switched)

  4. can be used in .vue form or directly in the browser environment

  5. No more. . .

Directory structure

The first step is still to Create a project, it is just a single component, the structure is not complicated , Datepicker.vue is the most important component file, dist is the output folder of webpack, index.js is the entry file packaged by webpack, and finally the webpack configuration file is used to modify our library files. For packaging. So the project structure is like this:

.
├── Datepicker.vue
├── LICENSE
├── README.md
├── dist
│ └── vue-datepicker.js
├── index.js
├── package.json
└── webpack.config.js

Start with Datepicker.vue

Writing Vue components in .vue is a special way of writing. Each Vue file includes three parts: template, script, and style. , it is best not to use the template as a fragment instance, so the outermost layer is first covered with p, which is used as the root element of the entire component. A datepicker generally consists of two parts, an input box used to display the date, and a panel used to select the date. Because I found that input will automatically evoke the keyboard on the mobile terminal, I did not use input and directly used p simulation, by clicking The event determines the visibility of the panel. Value is the final result and needs to communicate with the parent component, so the value is written as prop, and value.sync="xxx" is used in the parent component. The value of the datepicker is bidirectionally bound to the xxx of the parent component.

<template>
 <p>
  </p>
<p>
 </p>
 <p>
 </p>
</template>
<scrip>
 export default {
  data () {
   return {
    panelState: false //初始值,默认panel关闭
   }
  },
  props: {
   value: String
  }
 }
</scrip>

Rendering date list

A month has at least 28 days. If Sunday is arranged at the beginning, then at least 4 lines are needed (the 1st happens to be Sunday), but the number of days in each month Most of them are 30 or 31, and the 1st is not necessarily Sunday, so I simply designed it according to the most common situation, with a total of 6 rows. The unfilled parts of the current month's date are filled with the dates of the previous month or the next month, so that It is easy to calculate, and the panel height will not change when switching months. The array of date lists needs to be calculated dynamically. Vue provides the computed attribute, so the date list dateList is directly written as a calculated attribute. My method is to fix the date list into an array with a length of 42, and then fill it with the dates of this month, last month, and next month in sequence.

computed: {
 dateList () {
  //获取当月的天数
  let currentMonthLength = new Date(this.tmpMonth, this.tmpMonth + 1, 0).getDate()
  //先将当月的日期塞入dateList
  let dateList = Array.from({length: currentMonthLength}, (val, index) => {
   return {
    currentMonth: true,
    value: index + 1
   }
  })
  //获取当月1号的星期是为了确定在1号前需要插多少天
  let startDay = new Date(this.year, this.tmpMonth, 1).getDay()
  //确认上个月一共多少天
  let previousMongthLength = new Date(this.year, this.tmpMonth, 0).getDate()
 }
 //在1号前插入上个月日期
 for(let i = 0, len = startDay; i <p style="text-align: left;">Here, Array.from is used to initialize an array, an Array Like is passed in, and converted into an array. When splicing strings, arr[arr.length] and [{}].concat(arr are used ) this way, because I learned on JsTips that it performs better this way, and relevant links will be posted at the end of the article. <br>In this way, the date list is constructed, and is rendered using a v-for loop in the template. </p><pre class="brush:php;toolbar:false">
     
  •  

You can use the style yourself and write it however you like. It should be noted that the cycle date may appear last month or this month. I marked it through previuosMonth, currentMonth and nextMonth respectively to provide judgment conditions for other functions.
The year and month lists are similar. I wrote the initial value of the year list directly in the data, with the current year as the first one. In order to be consistent with the month, 12 are displayed each time through v. -for rendering.

data () {
 return {
  yearList: Array.from({length: 12}, (value, index) => new Date().getFullYear() + index)
 }
}

Select date function

The selection order is: year-> month-> day, so we can control the content displayed in the panel through a state variable and bind the appropriate function Switch display status.

<p>
 </p><p>
  </p>
       
  •    
  •   
   

  

       
  •    
  •   
   

  

       
  •    
  •   
 

选择日期的方法就不细说了,在selectYear,selectMonth中对年份,月份变量赋值,再分别将panelType推向下一步就实现了日期选择功能。

不过在未选择完日期之前,你可能不希望当前年月的真实值发生变化,所以在这些方法中可先将选择的值赋给一个临时变量,等到seletDate的时候再一次性全部赋值。

selectMonth (month) {
 if(this.validateMonth(month)){
  return
 }else{
  //临时变量
  this.tmpMonth = month
  //切换panel状态
  this.panelType = 'date'
 }
},
selectDate (date) {
 //validate logic above...
 //一次性全部赋值
 this.year = tmpYear
 this.month = tmpMonth
 this.date = date.value
 this.value = `${this.tmpYear}-${('0' + (this.month + 1)).slice(-2)}-${('0' + this.date).slice(-2)}`
 //选择完日期后,panel自动隐藏
 this.panelState = false
}

最大/小时间限制

最大/小值是需要从父组件传递下来的,因此应该使用props,另外,这个值可以是字符串,也应该可以是变量(比如同时存在两个datepicker,第二个的日期不能比第一个大这种逻辑),所以应该使用Dynamically bind的方式传值。

<datepicker></datepicker>
<!-- 现在min的值会随着start的变化而变化 -->
<datepicker></datepicker>

增加了限制条件,对于不合法的日期,其按钮应该变为置灰状态,我用了比较时间戳的方式来判断日期是否合法,因为就算当前panel中的日期是跨年或是跨月的,通过日期构造函数创建时都会帮你转换成对应的合法值,省去很多判断的麻烦:

new Date(2015, 0, 0).getTime() === new Date(2014, 11, 31).getTime() //true
new Date(2015, 12, 0).getTime() === new Date(2016, 0, 0).getTime() //true

因此验证日期是否合法的函数是这样的:

validateDate (date) {
 let mon = this.tmpMonth
 if(date.previousMonth){
  mon -= 1
 }else if(date.nextMonth){
  mon += 1
 }
 if(new Date(this.tmpYear, mon, date.value).getTime() >= new Date(this.minYear, this.minMonth - 1, this.minDate).getTime()
  && new Date(this.tmpYear, mon, date.value).getTime() <h2 id="动态计算位置">动态计算位置</h2><p style="text-align: left;">当页面右侧有足够的空间显示时,datepicker的panel会定位为相对于父元素left: 0的位置,如果没有足够的空间,则应该置于right: 0的位置,这一点可以通过Vue提供的动态样式和样式对象来实现(动态class和动态style其实只是动态props的特例),而计算位置的时刻,我放在了组件声明周期的ready周期中,因为这时组件已经插入到DOM树中,可以获取style进行动态计算:</p><pre class="brush:php;toolbar:false">ready () {
 if(this.$el.parentNode.offsetWidth + this.$el.parentNode.offsetLeft - this.$el.offsetLeft 
<p></p>

为了panel的显隐可以平滑过渡,可以使用transition做过渡动画,这里我简单地通过一个0.2秒的透明度过渡让显隐更平滑。

<p></p>
//less syntax
.toggle{
 &-transition{
  transition: all ease .2s;
 }
 &-enter, &-leave{
  opacity: 0;
 }
}

中英文切换

这里其实也很简单,这种多语言切换实质就是一个key根据不同的type而输出不同的value,所以使用filter可以很容易的实现它!比如渲染星期的列表:


      
  •  
  filters : {  week (item, lang){   switch (lang) {    case 'en':     return {0: 'Su', 1: 'Mo', 2: 'Tu', 3: 'We', 4: 'Th', 5: 'Fr', 6: 'Sa'}[item]    case 'ch':     return {0: '日', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六'}[item]    default:     return item   }  } }

多种使用方式

对于一个Vue组件,如果是使用webpack + vue-loader的.vue单文件写法,我希望这样使用:

//App.vue
<script>
 import datepicker from &#39;path/to/datepicker.vue&#39;
 export default {
  components: { datepicker}
 }
</script>

如果是直接在浏览器中使用,那么我希望datepicker这个组件是暴露在全局下的,可以这么使用:

//index.html

 <script></script>
 <script></script>
 
  <p></p>
  <script>
   new Vue({
    el: &#39;#app&#39;,
    components: { datepicker }
   })
  </script>
 

这里我选择了webpack作为打包工具,使用webpack的output.library和output.linraryTarget这两个属性就可以把你的bundle文件作为库文件打包。library定义了库的名字,libraryTarget定义了你想要打包的格式,具体可以看文档。我希望自己的库可以通过datepicker加载到,并且打包成umd格式,因此我的webpack.config.js是这样的:

module.exports = {
 entry: './index.js',
 output: {
  path: './dist',
  library: 'datepicker',
  filename: 'vue-datepicker.js',
  libraryTarget: 'umd'
 },
 module: {
  loaders: [
   {test: /\.vue$/, loaders: ['vue']},
   {test: /\.js$/, exclude: /node_modules/, loaders: ['babel']}
  ]
 }
}

打包完成的模块就是一个umd格式的模块啦,可以在浏览器中直接使用,也可以配合require.js等模块加载器使用!

适配 Vue 2.x

Vue 2.0已经发布有段时间了,现在把之前的组件适配到Vue 2.0。迁移过程还是很顺利的,核心API改动不大,可以借助vue-migration-helper来找出废弃的API再逐步修改。这里只列举一些我需要修改的API。

filter

2.0中的filter只能在mustache绑定中使用,如果想在指令式绑定中绑定过滤后的值,可以选择计算属性。我在月份和星期的显示中使用到了过滤器来过滤语言类型,但我之前是在指令式绑定中使用的filter,所以需要如下修改,:

//修改前
<p></p>
//修改后,filter传参的方式也变了,变成了函数调用的风格
<p>{{tmpMonth + 1 | month(language)}}</p>

移除$index和$key

这两个属性不会在v-for中被自动创建了,如需使用,要在v-for中自行声明:


  • //
  • ready 生命周期移除

    ready从生命周期钩子中移除了,迁移方法很简单,使用mounted和this.$nextTick来替换。

    prop.sync弃用

    prop的sync弃用了,迁移方案是使用自定义事件,而且Datepicker这种input类型组件,可以使用表单输入组件的自定义事件作为替换方案。自定义组件也可以使用v-model指令了,但是必须满足两个条件:

    1. 接收一个value的prop

    2. 值发生变化时,触发一个input事件,传入新值。

    所以Datepicker的使用方式也不是了,而是。组件自身向父级传值的方式也不一样了:

    //1.x版本,设置了value的值会同步到父级
    this.value = `${this.tmpYear}-${('0' + (this.month + 1)).slice(-2)}-${('0' + this.date).slice(-2)}`
    //2.x版本,需要自己触发input事件,将新值作为参数传递回去
    let value = `${this.tmpYear}-${('0' + (this.month + 1)).slice(-2)}-${('0' + this.date).slice(-2)}`
    this.$emit('input', value)

    相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

    推荐阅读:

    datepicker插件监听输入框

    NavigatorIOS组件的使用详解

    ejsExcel模板在Vue.js中的使用

    The above is the detailed content of How to use datepicker. For more information, please follow other related articles on the PHP Chinese website!

  • Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

    The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Tools

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.