Home > Web Front-end > JS Tutorial > body text

How to implement a calendar using Vue components (detailed tutorial)

亚连
Release: 2018-06-13 10:35:38
Original
3572 people have browsed it

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>
Copy after login
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,
 },
});
Copy after login

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;
},
Copy after login

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;
 }
},
Copy after login

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;
 }
},
Copy after login

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;
 });
},
Copy after login

(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);
},
Copy after login

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;
},
Copy after login

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;,
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!