前端开发攻略---封装日历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

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

html 滚动条滚动过快会留下边框线的解决方案

《html滚动条滚动过快会留下边框线的解决方案》:本文主要介绍了html滚动条滚动过快会留下边框线的解决方案,解决方法很简单,详细内容请阅读本文,希望能对你有所帮助... 滚动条滚动过快时,会留下边框线但其实大部分时候是这样的,没有多出边框线的滚动条滚动过快时留下边框线的问题通常与滚动条样式和滚动行

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

使用vscode搭建pywebview集成vue项目实践

《使用vscode搭建pywebview集成vue项目实践》:本文主要介绍使用vscode搭建pywebview集成vue项目实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录环境准备项目源码下载项目说明调试与生成可执行文件核心代码说明总结本节我们使用pythonpywebv

C++ RabbitMq消息队列组件详解

《C++RabbitMq消息队列组件详解》:本文主要介绍C++RabbitMq消息队列组件的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. RabbitMq介绍2. 安装RabbitMQ3. 安装 RabbitMQ 的 C++客户端库4. A

使用Python和Tkinter实现html标签去除工具

《使用Python和Tkinter实现html标签去除工具》本文介绍用Python和Tkinter开发的HTML标签去除工具,支持去除HTML标签、转义实体并输出纯文本,提供图形界面操作及复制功能,需... 目录html 标签去除工具功能介绍创作过程1. 技术选型2. 核心实现逻辑3. 用户体验增强如何运行

CSS 样式表的四种应用方式及css注释的应用小结

《CSS样式表的四种应用方式及css注释的应用小结》:本文主要介绍了CSS样式表的四种应用方式及css注释的应用小结,本文通过实例代码给大家介绍的非常详细,详细内容请阅读本文,希望能对你有所帮助... 一、外部 css(推荐方式)定义:将 CSS 代码保存为独立的 .css 文件,通过 <link> 标签

使用Vue-ECharts实现数据可视化图表功能

《使用Vue-ECharts实现数据可视化图表功能》在前端开发中,经常会遇到需要展示数据可视化的需求,比如柱状图、折线图、饼图等,这类需求不仅要求我们准确地将数据呈现出来,还需要兼顾美观与交互体验,所... 目录前言为什么选择 vue-ECharts?1. 基于 ECharts,功能强大2. 更符合 Vue