search
HomeWeb Front-endJS TutorialHow 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 &#39;./components/DatePicker.vue&#39;;
import &#39;./style.scss&#39;;
new Vue({
 el: &#39;#app&#39;,
 data() {
 return {
 date: &#39;2017-09-11&#39;,
 minDate: &#39;2000-09-11&#39;,
 maxDate: &#39;2020-09-11&#39;,
 showDatePicker: false,
 selectedDate: &#39;点击选择日期&#39;,
 };
 },
 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 = &#39;fadeX_Prev&#39;;
 // 如何当前月份已经小于等于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 = &#39;fadeX_Next&#39;;
 // 如何当前月份已经大于等于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 = &#39;copyMinDate&#39;;
 } else if (this.isMaxLimitMonth()) { // 当日期在最大值之外,月份换成最大值月份
 type = &#39;copyMaxDate&#39;;
 }
 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(&#39;-&#39;);
 try {
 if (!splitValue || splitValue.length < 3) {
 throw new Error(&#39;时间格式不正确&#39;);
 }
 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: &#39;&#39;,
month: &#39;&#39;,
day: &#39;&#39;,
week: &#39;&#39;,
weekStr: &#39;&#39;,
monthStr: &#39;&#39;,

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!

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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools