search
HomeWeb Front-endVue.jsDetailed explanation of how to use vue to encapsulate a custom calendar component

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>

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,
  },
];复制代码

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([]);复制代码

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();
}复制代码

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

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)