How to implement a calendar using Vue components (detailed tutorial)
Components are a must-know part of learning vue. The following article mainly introduces you to the relevant information about the Vue component (component) tutorial to implement a beautiful calendar. The article introduces it in great detail through sample code, which is very useful for everyone. Studying or working has certain reference learning value. Friends who need it, please follow me to learn together.
Component is one of the most powerful features of Vue. Components can extend HTML elements, encapsulate reusable code, and abstract some components according to project requirements. Each component includes presentation, functionality, and style. Each page uses different components to splice the page according to its own needs. This development model makes the front-end page easy to expand and highly flexible, and also achieves decoupling between components.
Recently, at the request of the company, I need to develop a beautiful calendar component (can run on IOS, Android, and IE9 on PC). After I finish writing it, I want to share it and hope everyone can criticize it.
Let’s take a screenshot first
The code has been shared to https://github.com/zhangKunUserGit/vue-component (local Download)
How to use
Let me tell you how to use it according to your needs (the above is: HTML, the following is JS)
<date-picker v-if="showDatePicker" :date="date" :min-date="minDate" :max-date="maxDate" @confirm="confirm" @cancel="cancel" ></date-picker>
import DataPicker from './components/DatePicker.vue'; import './style.scss'; new Vue({ el: '#app', data() { return { date: '2017-09-11', minDate: '2000-09-11', maxDate: '2020-09-11', showDatePicker: false, selectedDate: '点击选择日期', }; }, methods: { openDatePicker() { this.showDatePicker = true; }, confirm(value) { this.showDatePicker = false; this.selectedDate = value; }, cancel() { this.showDatePicker = false; }, }, components: { DataPicker, }, });
We provide the maximum value, minimum value and initial value. The only shortcoming is that the time format can only be YYYY-MM-DD (2017-12-12). You can pull the code from github and run it to have a look ( Since it has not been carefully tested, there may be bugs and performance issues, I hope they will be pointed out).
(1) Draw the interface first
This is not the point, HTML and CSS should be very simple, you may feel it when you look at my css My name is too long, just because our company uses it, and I am worried that other styles will affect it (there may be other ways, I hope someone can point it out)
(2) Assembly date list
Look at the code first:
rows() { const { year, month } = this.showDate; const months = (new Date(year, month, 0)).getDate(); const result = []; let row = []; let weekValue; // 按照星期分组 for (let i = 1; i <= months; i += 1) { // 根据日期获取星期,并让开头是1,而非0 weekValue = (new Date(year, month, i)).getDay() + 1; // 判断月第一天在星期几,并填充前面的空白区域 if (i === 1 && weekValue !== 1) { this.addRowEmptyValue(row, weekValue); this.addRowDayValue(row, i); } else { this.addRowDayValue(row, i); // 判断月最后一天在星期几,并填充后面的空白区域 if (i === months && weekValue !== 7) { this.addRowEmptyValue(row, (7 - weekValue) + 1); } } // 按照一周分组 if (weekValue % 7 === 0 || i === months) { result.push(row); row = []; } } this.showDate.monthStr = monthJson[this.showDate.month]; return result; },
My idea is:
(1) Get the number of days in the month and group them by week;
(2) If the first day of the month is not Monday, fill in the front with null values. In the same way, if the last day of the month is not on Sunday, fill in the null value at the end. The purpose is: the length of the handicap group is 7, which is one week. In this way, you can develop quickly using flex layout;
(3) It also contains some restrictions, such as less than minDate and greater than maxDate, not allowed to click, etc.
( 3) Switch the month
(1) The previous month
/** * 切换到上一个月 */ prevMonth() { if (this.prevMonthClick) { return; } this.prevMonthClick = true; setTimeout(() => { this.prevMonthClick = false; }, 500); this.fadeXType = 'fadeX_Prev'; // 如何当前月份已经小于等于minMonth 就不让其在执行 if (this.isMinLimitMonth()) { return; } const { year, month } = this.showDate; // 判断当前月份,如果已经等于1(1就是一月,而不是二月) if (month <= 1) { this.showDate.year = year - 1; this.showDate.month = 12; } else { this.showDate.month -= 1; } },
setTimeout() is mainly to make it disappear automatically after displaying animation. fadeXType is the animation type
(2) Next month
/** * 切换到下一个月 */ nextMonth() { if (this.nextMonthClick) { return; } this.nextMonthClick = true; setTimeout(() => { this.nextMonthClick = false; }, 500); this.fadeXType = 'fadeX_Next'; // 如何当前月份已经大于等于maxMonth 就不让其在执行 if (this.isMaxLimitMonth()) { return; } const { year, month } = this.showDate; // 判断当前月份,如果已经等于12(12就是十二月) if (month >= 12) { this.showDate.year = year + 1; this.showDate.month = 1; } else { this.showDate.month += 1; } },
The principle of setTimeout() here is the same as the prevMonth method.
The above two functions of switching months mainly pay attention to:
a. Because there are minDate and maxDate, the first consideration is not to exceed this limit.
b. It is necessary to consider the change of the year after switching the month. When the month is greater than 12, the year is added by 1 and the month becomes 1.
(4) Select the year
(1) Click on the top year to display the year list
openYearList() { if (this.showYear) { this.showYear = false; return; } const index = this.yearList.indexOf(this.selectDate.year); this.showYear = true; // 打开年列表,让其定位到选中的位置上 setTimeout(() => { this.$refs.yearList.scrollTop = (index - 3) * 40; }); },
(2) Select the year
selectYear(value) { this.showYear = false; this.showDate.year = value; let type; // 当日期在最小值之外,月份换成最小值月份 或者 当日期在最大值之外,月份换成最大值月份 if (this.isMinLimitMonth()) { type = 'copyMinDate'; } else if (this.isMaxLimitMonth()) { // 当日期在最大值之外,月份换成最大值月份 type = 'copyMaxDate'; } if (type) { this.showDate.month = this[type].month; this.showDate.day = this[type].day; this.resetSelectDate(this.showDate.day); return; } let dayValue = this.selectDate.day; // 判断日是最大值,防止另一个月没有这个日期 if (this.selectDate.day > 28) { const months = (new Date(this.showDate.year, this.showDate.month, 0)).getDate(); // 当前月份没有这么多天,就把当前月份最大值赋值给day dayValue = months < dayValue ? months : dayValue; } this.resetSelectDate(dayValue); },
Pay attention to the following aspects when switching the year:
a. Consider minDate and maxDate, because if the month you selected before is January, but the limit is September, there is no problem in the year greater than minDate (such as 2017), but when it comes to the specific year of minDate (such as 2010), then the minimum value of the month can only It is September, the month needs to be modified, and the same applies to maxDate.
b. The day you selected before was 31. Since after switching the year, this month only has 30 days, remember to change day to the maximum value of this month, which is 30.
(5) Processing original data
In fact, under normal circumstances, this item should be discussed in the first step, but I am basing it on my Use development habits to write steps. I usually write the function first, and the data is simulated. After it is written, I will consider the original data format and specific exposure methods, etc., because this way I will not change it over and over again, which will affect the development and mood.
initDatePicker() { this.showDate = { ...this.splitDate(this.date, true) }; this.copyMinDate = { ...this.splitDate(this.minDate) }; this.copyMaxDate = { ...this.splitDate(this.maxDate) }; this.selectDate = { ...this.showDate }; }, splitDate(date, addStr) { let result = {}; const splitValue = date.split('-'); try { if (!splitValue || splitValue.length < 3) { throw new Error('时间格式不正确'); } result = { year: Number(splitValue[0]), month: Number(splitValue[1]), day: Number(splitValue[2]), }; if (addStr) { result.week = (new Date(result.year, result.month, result.day)).getDay() + 1; result.monthStr = monthJson[result.month]; result.weekStr = weekJson[result.week]; } } catch (error) { console.error(error); } return result; },
The purpose here is:
a. Process the original data, check the original data, and cache it with json, so as to facilitate subsequent operations and display. I am only compatible with the YYYY-MM-DD format, and other formats are not compatible. If you want to be compatible with other formats, you can modify the code, or use other libraries such as moment.js to help you do this.
b. The split format is as follows:
year: '', month: '', day: '', week: '', weekStr: '', monthStr: '',
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
related articles:
How does requireJS implement a module loader?
Implementing the MVVM framework in js (detailed tutorial)
Explanation of scope scope in angularjs
How to implement high-performance loading sequence in javascript
How to implement global registration in axios
The above is the detailed content of How to implement a calendar using Vue components (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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 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 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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools