Home > Web Front-end > Vue.js > body text

Detailed explanation of how to use vue to encapsulate a custom calendar component

青灯夜游
Release: 2023-04-02 07:30:02
forward
2019 people have browsed it

How to develop a custom calendar vue component. The following article will teach you step by step how to encapsulate a custom calendar component. I hope it will be helpful to everyone!

Detailed explanation of how to use vue to encapsulate a custom calendar component

As we all know, generally speaking, if a calendar component is needed in a project, it is often found in third-party UI libraries or ready-made components. Other third-party plug-ins. For many friends, when they first see the calendar component, they subconsciously think it is very complicated and have no way to start. But when I read the source code of this calendar plug-in, I found that it was not as complicated as I thought. I used to foolishly think that if I wanted to make a calendar component, I would need to obtain calendar data for at least ten years before and after the current year before proceeding with the next step of development.

However, after I tried to read the source code of dycalendar.js, on the one hand, I felt that I was too stupid and thought of the problem too complicated. I also admire the author's clear thinking. After reading it, I felt that I benefited a lot.

After sorting out the author's idea logic, I developed a vue component based on this idea. As shown in the picture below:

Detailed explanation of how to use vue to encapsulate a custom calendar component

#Next, follow me to see how to develop your own calendar component. [Related recommendations: vuejs video tutorial, web front-end development]

Core code implementation

1. Sorting out ideas

  • Get the target date data
  • Get the important attributes of the current date, such as current year, current month, current date , The current day of the week,The total number of days in the current month,The first day of the current month corresponds to the day of the week,The total number of days in the last month How many days to wait.
  • Based on these attributes, generate a specific calendar date data list, and then render it into the template in a loop.
  • When switching months, obtain various key data corresponding to the new target date. After vue detects changes in calendar attributes, the notification page is updated.

2. Data required for initialization

Generally speaking, in mature calendar components, the date is a two-way bound variable. For ease of use, we also use two-way binding.

<script>import { reactive, ref, computed, watch } from "vue";const props = defineProps({  modelValue: Date,
});const emits = defineEmits(["update:modelValue"]);/**
 * 最小年份
 */const MIN_YEAR = 1900;/**
 * 最大年份
 */const MAX_YEAR = 9999;/**
 * 目标日期
 */const targetDate = ref(props.modelValue);复制代码</script>
Copy after login

Next, we also need to initialize some constants to represent the month and date:

/**
 * 有关月度的名称列表
 */const monthNameList = {  chineseFullName: [    "一月",    "二月",    "三月",    "四月",    "五月",    "六月",    "七月",    "八月",    "九月",    "十月",    "十一月",    "十二月",
  ],  fullName: [    "January",    "February",    "March",    "April",    "May",    "June",    "July",    "August",    "September",    "October",    "November",    "December",
  ],  mmm: [    "Jan",    "Feb",    "Mar",    "Apr",    "May",    "Jun",    "Jul",    "Aug",    "Sep",    "Oct",    "Nov",    "Dec",
  ],
};/**
 * 有关周几的名称列表
 */const dayNameList = [
  {    chineseFullName: "周日",    chineseShortName: "日",    fullName: "Sunday",    shortName: "Sun",    dayNumber: 0,
  },
  {    chineseFullName: "周一",    chineseShortName: "一",    fullName: "Monday",    shortName: "Mon",    dayNumber: 1,
  },
  {    chineseFullName: "周二",    chineseShortName: "二",    fullName: "Tuesday",    shortName: "Tue",    dayNumber: 2,
  },
  {    chineseFullName: "周三",    chineseShortName: "三",    fullName: "Wednesday",    shortName: "Wed",    dayNumber: 3,
  },
  {    chineseFullName: "周四",    chineseShortName: "四",    fullName: "Thursday",    shortName: "Thu",    dayNumber: 4,
  },
  {    chineseFullName: "周五",    chineseShortName: "五",    fullName: "Friday",    shortName: "Fri",    dayNumber: 5,
  },
  {    chineseFullName: "周六",    chineseShortName: "六",    fullName: "Saturday",    shortName: "Sat",    dayNumber: 6,
  },
];复制代码
Copy after login

Next, prepare several vue responsive data:

/**
 * 今日
 */const today = new Date();/**
 * 日历的各项属性
 */const calendarProps = reactive({  target: {    year: null,    month: null,    date: null,    day: null,    monthShortName: null,    monthFullName: null,    monthChineseFullName: null,    firstDay: null,    firstDayIndex: null,    totalDays: null,
  },  previous: {    totalDays: null,
  },
});/**
 * 用于展现的日历数据
 */const calendarData = ref([]);复制代码
Copy after login

3 , Initialize the various attributes of the calendar

Next, obtain the various attributes of the calendar through the setCalendarProps method, and fill in the data in calendarProps one by one:

function setCalendarProps() {  if (!targetDate.value) {
    targetDate.value = today;
  }  // 获取目标日期的年月日星期几数据
  calendarProps.target.year = targetDate.value.getFullYear();
  calendarProps.target.month = targetDate.value.getMonth();
  calendarProps.target.date = targetDate.value.getDate();
  calendarProps.target.day = targetDate.value.getDay();  if (
    calendarProps.target.year  MAX_YEAR
  ) {    console.error("无效的年份,请检查传入的数据是否是正常");    return;
  }  // 获取到目标日期的月份【中文】名称
  let dateString;
  dateString = targetDate.value.toString().split(" ");
  calendarProps.target.monthShortName = dateString[1];
  calendarProps.target.monthFullName =
    monthNameList.fullName[calendarProps.target.month];
  calendarProps.target.monthChineseFullName =
    monthNameList.chineseFullName[calendarProps.target.month];  // 获取目标月份的第一天是星期几,和在星期几中的索引值
  const targetMonthFirstDay = new Date(
    calendarProps.target.year,
    calendarProps.target.month,    1
  );
  calendarProps.target.firstDay = targetMonthFirstDay.getDay();
  calendarProps.target.firstDayIndex = dayNameList.findIndex(    (day) => day.dayNumber === calendarProps.target.firstDay
  );  // 获取目标月份总共多少天
  const targetMonthLastDay = new Date(
    calendarProps.target.year,
    calendarProps.target.month + 1,    0
  );
  calendarProps.target.totalDays = targetMonthLastDay.getDate();  // 获取目标月份的上个月总共多少天
  const previousMonth = new Date(
    calendarProps.target.year,
    calendarProps.target.month,    0
  );
  calendarProps.previous.totalDays = previousMonth.getDate();
}复制代码
Copy after login

One thing to note is that when getting the number of days in this month and the number of days in last month, the date value is set to 0. This is because when the date value is 0, the returned Date object is the last day of the previous month. So, in order to get the number of days in this month, you need to add 1 to the month value of this month.

After executing this method, the value of calendarProps at this time is:

Detailed explanation of how to use vue to encapsulate a custom calendar component

4. Generate calendar dates based on calendar attributes The data

When we already knowThe day of the week index value corresponding to the first day of this month,How many days are there in this monthandThe total number of days in last month How many daysAfter these three core data, you can start to generate the corresponding calendar data.

The idea is as follows:

  1. Since in most cases, the first day of this month does not start from the beginning, the previous part is the date of the previous month . So the first line needs to be processed separately.
  2. Set a public date value, and the initial value is set to 1. Then start incrementing from the day of the week index value corresponding to the first day of this month. Set an algorithm to calculate dates before and after this month.
  3. In order to facilitate date switching and style differentiation later, the generated data is processed into an object, which contains the date type -
  4. dateType, indicating whether it is this month, the previous month, or the next month;
  5. /**
     * 生成日历的数据
     */function setCalendarData() {  let i;  let date = 1;  const originData = [];  const firstRow = [];  // 设置第一行数据
      for (i = 0; i 
    Copy after login
At this point, the core logic of this calendar component has been implemented. Look, isn’t it very simple?

Next, we only need to render the corresponding html template and add styles based on the data in

calendarData.

5. Add the template and style part

Generally speaking, calendar components have a grid-like structure, so I choose the table method for rendering. But if you ask me if there are other ways, there are still some, such as using flex layout or grid layout, but if this method is used, the data structure of calendarData will not be what it is now.

The dom structure is as shown below:

Detailed explanation of how to use vue to encapsulate a custom calendar component

As for the flowing effect of the button border, I made it with reference to Su Su’s article. For details, please see:

Clip-path implements button flowing border animationjuejin.cn/post/719877…

Then the remaining style part can be improvised or based on UI design Just draw the picture. I believe you all have experienced the exquisite design drawings of UI sisters (heehee

The specific code part will not be posted in the article. If necessary, you can directly view the complete source code below

gitee.com/wushengyuan…

Conclusion

Some components that feel very troublesome may have core logic that is not so Complex. Sometimes, you may just need some patience, disassemble the code line by line, read it, and clarify the ideas.

(Learning video sharing: vuejs introductory tutorial,Basic Programming Video)

The above is the detailed content of Detailed explanation of how to use vue to encapsulate a custom calendar component. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.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!