Home > Web Front-end > Vue.js > An in-depth analysis of how to encapsulate a vue custom calendar component

An in-depth analysis of how to encapsulate a vue custom calendar component

藏色散人
Release: 2023-04-06 15:12:40
forward
2306 people have browsed it

This article brings you relevant knowledge about front-end calendars. It mainly talks about how to encapsulate a custom calendar component. Friends who are interested can take a look below. I hope it will be helpful to everyone.

Preface

As we all know, generally speaking, if there is a need to use the calendar component in a project, it is often found to use components in third-party UI libraries, or to find 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:

An in-depth analysis of how to encapsulate a vue custom calendar component

#Next, follow me to see how to develop your own calendar component.

Core code implementation

1. Sort out ideas

  • Get the target date data
  • Get the important attributes of the current date, such as Current year, Current month, Current date, Current day of the week, There are total 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, etc.
  • 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 setup>
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);
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 properties of the calendar

Next, obtain the various properties 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 < MIN_YEAR ||
    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:

An in-depth analysis of how to encapsulate a vue 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 <= 6; i++) {
        // 设置目标月份之前月份的日期数据
        if (i < calendarProps.target.firstDayIndex) {
          const previousDate =
            calendarProps.previous.totalDays -
            calendarProps.target.firstDayIndex +
            (i + 1);
          firstRow.push({
            dateObj: new Date(
              calendarProps.target.year,
              calendarProps.target.month - 1,
              previousDate
            ),
            dateNumber: previousDate,
            dateType: "previous"
          });
        } else {
          // 设置目标月份当月的日期数据
          firstRow.push({
            dateObj: new Date(
              calendarProps.target.year,
              calendarProps.target.month,
              date
            ),
            dateNumber: date,
            dateType: "current"
          });
          date++;
        }
      }
      originData.push(firstRow);
      // 设置后面五行的数据
      for (let j = 0; j <= 4; j++) {
        const rowData = [];
        for (let k = 0; k <= 6; k++) {
          // 设置目标月份剩下的日期数据
          if (date <= calendarProps.target.totalDays) {
            rowData.push({
              dateObj: new Date(
                calendarProps.target.year,
                calendarProps.target.month,
                date
              ),
              dateNumber: date,
              dateType: "current"
            });
          } else {
            // 设置目标月份下个月的日期数据
            const nextDate = date - calendarProps.target.totalDays;
            rowData.push({
              dateObj: new Date(
                calendarProps.target.year,
                calendarProps.target.month + 1,
                nextDate
              ),
              dateNumber: nextDate,
              dateType: "next"
            });
          }
          date++;
        }
        originData.push(rowData);
      }
      calendarData.value = originData;
    }
    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:

    An in-depth analysis of how to encapsulate a vue 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 (hee hee

    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.

    Recommended study: "vue video tutorial"

The above is the detailed content of An in-depth analysis of how to encapsulate a vue custom calendar component. For more information, please follow other related articles on the PHP Chinese website!

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