前端开发攻略---封装日历calendar组件(纯手搓),可以根据您的需求任意改变,可玩性强

本文主要是介绍前端开发攻略---封装日历calendar组件(纯手搓),可以根据您的需求任意改变,可玩性强,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、演示

2、代码

<template><div class="box" v-if="startMonth.year"><div class="left"><div class="top"><span class="iconfont" @click="changeMonth(-1)">左</span><span>{{ startMonth.year }}年{{ startMonth.month }}月</span><span></span></div><div class="calendarMain"><div class="weeks"><span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span></div><div class="days"><divclass="day"v-for="item in startMonth.dates":class="monthDaysClass(item)":style="[{ '--ml': item.week }]"@mouseenter="dayMouseMove(item)"@click="dayMouseClick(item)">{{ item.day }}</div></div></div></div><div class="right"><div class="top"><span></span><span>{{ endMonth.year }}年{{ endMonth.month }}月</span><span class="iconfont" @click="changeMonth(1)">右</span></div><div class="calendarMain"><div class="weeks"><span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span></div><div class="days"><divclass="day"v-for="item in endMonth.dates":class="monthDaysClass(item)":style="[{ '--ml': item.week }]"@mouseenter="dayMouseMove(item)"@click="dayMouseClick(item)">{{ item.day }}</div></div></div></div></div>
</template><script setup>
import { ref, reactive, onMounted } from 'vue'
const currentDateIndex = ref(0)
const startMonth = ref({})
const endMonth = ref({})
const selectDate = ref([])
const isMove = ref(false)onMounted(() => {initCalendar()
})const initCalendar = () => {getCalendarData()const startIndex = startMonth.value.dates.findIndex(item => !item.isTodayBefore)if (startIndex == startMonth.value.dates.length - 1) {selectDate.value[0] = startMonth.value.dates[startIndex].yymmddselectDate.value[1] = endMonth.value.dates[0].yymmdd} else {selectDate.value[0] = startMonth.value.dates[startIndex].yymmddselectDate.value[1] = startMonth.value.dates[startIndex + 1].yymmdd}
}const getCalendarData = () => {startMonth.value = getMonthDates(currentDateIndex.value)endMonth.value = getMonthDates(currentDateIndex.value + 1)
}
const changeMonth = num => {currentDateIndex.value += numgetCalendarData()
}const monthDaysClass = item => {if (item.isTodayBefore) return 'disabled'if (item.yymmdd == selectDate.value[0]) return 'active'if (item.yymmdd == selectDate.value[1]) return 'active'if (getDatesBetween(selectDate.value[0], selectDate.value[1]).includes(item.yymmdd)) return 'middle'
}const getDatesBetween = (date1, date2) => {let dates = []let currentDate = new Date(date1)let endDate = new Date(date2)while (currentDate < endDate) {let dateString = currentDate.toISOString().substr(0, 10)dates.push(dateString)currentDate.setDate(currentDate.getDate() + 1)}if (dates.length > 0) {dates.shift()}return dates
}const dayMouseClick = item => {if (item.isTodayBefore) returnlet arr = [...selectDate.value]if (!isMove.value) {if (arr.length == 1) {arr[1] = item.yymmdd} else {arr = []arr[0] = item.yymmdd}isMove.value = true} else {isMove.value = false}if (arr[0] > arr[1]) {selectDate.value = arr.reverse()} else {selectDate.value = arr}console.log(selectDate.value)
}const dayMouseMove = item => {if (item.isTodayBefore) returnif (!isMove.value) returnselectDate.value[1] = item.yymmdd
}function getMonthDates(monthOffset) {const today = new Date()const targetDate = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1)const year = targetDate.getFullYear()let month = targetDate.getMonth() + 1 // 月份是从0开始的,所以要加1month = month >= 10 ? month : '0' + monthconst firstDay = new Date(year, targetDate.getMonth(), 1)const lastDay = new Date(year, targetDate.getMonth() + 1, 0)const monthDates = []for (let d = firstDay; d <= lastDay; d.setDate(d.getDate() + 1)) {const day = d.getDate()const dayOfWeek = d.getDay() // 返回0到6,0代表星期日const isTodayBefore = d.getTime() < today.setHours(0, 0, 0, 0) // 判断是否是今天之前的日期monthDates.push({day,week: dayOfWeek,isTodayBefore,yymmdd: `${year}-${month}-${day >= 10 ? day : '0' + day}`,})}return { year, month, dates: monthDates }
}
</script><style scoped lang="scss">
.box {width: 793px;height: 436px;box-shadow: 2px 2px 6px #0003;display: flex;justify-content: space-between;padding: 30px 15px;.left,.right {width: 46%;height: 100%;.top {display: flex;justify-content: space-between;font-weight: bold;.iconfont {cursor: pointer;user-select: none;}}.calendarMain {.weeks {font-weight: bold;margin-top: 20px;display: flex;justify-content: space-between;& > span {display: inline-block;width: 50px;height: 50px;line-height: 50px;text-align: center;}}.days {display: flex;flex-wrap: wrap;cursor: pointer;.day {width: 50px;height: 50px;height: 50px;text-align: center;line-height: 50px;color: #111;font-size: 14px;}.day:nth-child(1) {margin-left: calc(var(--ml) * 50px);}.disabled {color: #ccc;cursor: not-allowed;}.active {background-color: #266fff;color: #fff;}.middle {background-color: rgba(38, 111, 255, 0.3);color: #fff;}}}}
}
</style>

3、代码解释

import { ref, reactive, onMounted } from 'vue'
import { useDatesBetween } from '@/hooks/time.js'

这里引入了 Vue 中的 ref 和 reactive 函数,以及 onMounted 钩子函数,以及从 time.js 模块中引入了 useDatesBetween 函数。

const currentDateIndex = ref(0)
const startMonth = ref({})
const endMonth = ref({})
const selectDate = ref([])
const getDatesBetween = useDatesBetween()
const isMove = ref(false)

创建了一些响应式变量,包括当前日期索引 currentDateIndex,起始月份 startMonth 和结束月份 endMonth 的引用,以及选择的日期范围 selectDateuseDatesBetween 函数的引用 getDatesBetween,以及一个标志 isMove,用于标记是否在移动状态。

onMounted(() => {initCalendar()
})

使用 onMounted 钩子,在组件挂载后执行 initCalendar 函数。

const initCalendar = () => {getCalendarData()const startIndex = startMonth.value.dates.findIndex(item => !item.isTodayBefore)if (startIndex == startMonth.value.dates.length - 1) {selectDate.value[0] = startMonth.value.dates[startIndex].yymmddselectDate.value[1] = endMonth.value.dates[0].yymmdd} else {selectDate.value[0] = startMonth.value.dates[startIndex].yymmddselectDate.value[1] = startMonth.value.dates[startIndex + 1].yymmdd}
}

initCalendar 函数初始化日历,获取日历数据并设置选择的日期范围。

const getCalendarData = () => {startMonth.value = getMonthDates(currentDateIndex.value)endMonth.value = getMonthDates(currentDateIndex.value + 1)
}

getCalendarData 函数获取当前月份和下个月份的日历数据。

const changeMonth = num => {currentDateIndex.value += numgetCalendarData()
}

changeMonth 函数根据给定的数字改变当前月份索引,并重新获取日历数据。

const monthDaysClass = item => {if (item.isTodayBefore) return 'disabled'if (item.yymmdd == selectDate.value[0]) return 'active'if (item.yymmdd == selectDate.value[1]) return 'active'if (getDatesBetween(selectDate.value[0], selectDate.value[1]).includes(item.yymmdd)) return 'middle'
}

monthDaysClass 函数根据日期项目返回对应的 CSS 类名,用于渲染日历中的日期。

const dayMouseClick = item => {if (item.isTodayBefore) returnlet arr = [...selectDate.value]if (!isMove.value) {if (arr.length == 1) {arr[1] = item.yymmdd} else {arr = []arr[0] = item.yymmdd}isMove.value = true} else {isMove.value = false}if (arr[0] > arr[1]) {selectDate.value = arr.reverse()} else {selectDate.value = arr}console.log(selectDate.value)
}

dayMouseClick 函数处理日期的点击事件,根据点击选择日期范围。

const dayMouseMove = item => {if (item.isTodayBefore) returnif (!isMove.value) returnselectDate.value[1] = item.yymmdd
}

dayMouseMove 函数处理鼠标移动事件,根据鼠标移动选择日期范围。

function getMonthDates(monthOffset) {const today = new Date()const targetDate = new Date(today.getFullYear(), today.getMonth() + monthOffset, 1)const year = targetDate.getFullYear()let month = targetDate.getMonth() + 1month = month >= 10 ? month : '0' + monthconst firstDay = new Date(year, targetDate.getMonth(), 1)const lastDay = new Date(year, targetDate.getMonth() + 1, 0)const monthDates = []for (let d = firstDay; d <= lastDay; d.setDate(d.getDate() + 1)) {const day = d.getDate()const dayOfWeek = d.getDay()const isTodayBefore = d.getTime() < today.setHours(0, 0, 0, 0)monthDates.push({day,week: dayOfWeek,isTodayBefore,yymmdd: `${year}-${month}-${day >= 10 ? day : '0' + day}`,})}return { year, month, dates: monthDates }
}

getMonthDates 函数根据月份偏移量获取该月的日期数据,包括年份、月份以及日期数组。

这篇关于前端开发攻略---封装日历calendar组件(纯手搓),可以根据您的需求任意改变,可玩性强的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/929637

相关文章

Olingo分析和实践之OData框架核心组件初始化(关键步骤)

《Olingo分析和实践之OData框架核心组件初始化(关键步骤)》ODataSpringBootService通过初始化OData实例和服务元数据,构建框架核心能力与数据模型结构,实现序列化、URI... 目录概述第一步:OData实例创建1.1 OData.newInstance() 详细分析1.1.1

从入门到精通详解LangChain加载HTML内容的全攻略

《从入门到精通详解LangChain加载HTML内容的全攻略》这篇文章主要为大家详细介绍了如何用LangChain优雅地处理HTML内容,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录引言:当大语言模型遇见html一、HTML加载器为什么需要专门的HTML加载器核心加载器对比表二

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

前端如何通过nginx访问本地端口

《前端如何通过nginx访问本地端口》:本文主要介绍前端如何通过nginx访问本地端口的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、nginx安装1、下载(1)下载地址(2)系统选择(3)版本选择2、安装部署(1)解压(2)配置文件修改(3)启动(4)

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动

HTML input 标签示例详解

《HTMLinput标签示例详解》input标签主要用于接收用户的输入,随type属性值的不同,变换其具体功能,本文通过实例图文并茂的形式给大家介绍HTMLinput标签,感兴趣的朋友一... 目录通用属性输入框单行文本输入框 text密码输入框 password数字输入框 number电子邮件输入编程框

HTML img标签和超链接标签详细介绍

《HTMLimg标签和超链接标签详细介绍》:本文主要介绍了HTML中img标签的使用,包括src属性(指定图片路径)、相对/绝对路径区别、alt替代文本、title提示、宽高控制及边框设置等,详细内容请阅读本文,希望能对你有所帮助... 目录img 标签src 属性alt 属性title 属性width/h

CSS3打造的现代交互式登录界面详细实现过程

《CSS3打造的现代交互式登录界面详细实现过程》本文介绍CSS3和jQuery在登录界面设计中的应用,涵盖动画、选择器、自定义字体及盒模型技术,提升界面美观与交互性,同时优化性能和可访问性,感兴趣的朋... 目录1. css3用户登录界面设计概述1.1 用户界面设计的重要性1.2 CSS3的新特性与优势1.

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF