Vue实现日历

本文介绍了如何使用Vue实现一个日历组件,包括计算本月天数、填充上个月和下个月日期、处理闰年情况以及切换年份和月份的方法。通过设置星期数组和月份数组,结合Vue代码片段,详细解析了日历渲染的关键步骤。

在这里插入图片描述
效果就是这样子,可以切换上一年,上一个月, 下一年,下一个月。

先来捋一下,

  1. 首先得知道本月有多少天
  2. 知道本月的第一天在星期几
  3. 将本月的天数从1号开始排
  4. 上一个月有多少天,将本月1号前的星期补全
  5. 本月的截止是星期几,下一个月1号从星期几遍历

STEP1:
先设置一个星期数组,用来存放星期日-星期一
月份数组来存放基本每月的天数

	week: string[] = ['日', '一', '二', '三', '四', '五', '六']
	monthList: number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

STEP2:
计算本月有多少天,并且1号是星期几

	const date = new Date()
    this.year = date.getFullYear()
    this.month = date.getMonth() + 1
    this.day = date.getDate()

	// 获得本月的1号是周一
    const firstDay = new Date(`${this.year}/${this.month}/1`).getDay()
    // 在1号前面填充多少个上个月的日期
    this.weekDay = firstDay === 7 ? 0 : firstDay

STEP3:
接下来一大步,就可以遍历本月的日期啦

vue代码片段

// 1号前的填充
<li v-for="inx in weekDay" class="disabled">
 	{{ preMonthSize - weekDay + inx }}
</li>
<li
    v-for="index in monthList[month - 1]"
 >
	<span :class="{ currentDay: index === day }" >
            {{ index }}
    </span>
</li>
// 月末的填充
<li v-for="index in lastWeekDay" class="disabled">{{ index }}</li>

由于monthList下标从0开始,所以month-1为当前月份天数。day为今天当index===day时加上一个小黄圈,表示今天。

STEP4
第三步将日期渲染出来了,并且填充了上个月和下个月。
接下来看一下第三步的变量是怎么来的

preMonthSize: 前一个月的天数

// 上一个月有多少天
  get preMonthSize() {
    return this.month - 1 === 0 ? 31 : this.monthList[this.month - 2] 
  }
   // 如果本月为1月,前一个月就是12月,肯定是31天。本月天数为this.monthList[this.month - 1],
   // 上月天数为this.monthList[this.month - 2]  .

weekDay:本月的1号是星期几(星期一)
本月的1号星期1,前面填充一个数字 , v-for数字的时候,从1开始(不是从0开始)

lastWeekDay:本月后填充几个下月的日期

// 获得本月的最后一天是星期几,往后填充多少个
const remineDay = new Date(`${this.year}/${this.month}/this.monthList[this.month - 1]`).getDay()
this.lastWeekDay = remineDay === 7 ? 6 : 6 - remineDay

至此本月的日历就渲染出来啦!
但是还有一个问题,闰年:
你可以在页面挂载的时候

if (
      (this.year % 4 === 0 && this.year % 100 !== 0) ||
      this.year % 400 === 0
    ) {
      this.monthList[1] = 29
    } else {
      this.monthList[1] = 28
    }

更改monthList的第二项。

STEP 5:
实现切月份年份。

 	<div class="canlendar-header">
      <p class="pre">
        <span @click="changeDate('preYear')">
          <icon class="icon" name="preYear" />
        </span>
        <span @click="changeDate('preMonth')">
          <icon class="icon" name="preMonth" />
        </span>
      </p>
      <p class="currenDate">{{ `${year}年${month}月` }}</p>
      <p class="next">
        <span @click="changeDate('nextMonth')">
          <icon class="icon" name="nextMonth" />
        </span>
        <span @click="changeDate('nextYear')">
          <icon class="icon" name="nextYear" />
        </span>
      </p>
    </div>

给每一个icon加上click函数,点击的时候传入不同的参数。

changeDate(type: string) {
    switch (type) {
      case 'preYear':
        this.year -= 1
        break
      case 'preMonth':
        // 当前月份为1月, 上一个月分为12月,年份减1
        if (this.month === 1) {
          this.month = 12
          this.year -= 1
        } else {
          this.month -= 1
        }
        break
      case 'nextYear':
        this.year += 1
        break
      case 'nextMonth':
        // 当前月份为12月, 下个月分为1月,年份加1
        if (this.month === 12) {
          this.month = 1
          this.year += 1
        } else {
          this.month += 1
        }
        break
      default:
        break
    }

    this.initDate()
  }

initDate() {
    if (
      (this.year % 4 === 0 && this.year % 100 !== 0) ||
      this.year % 400 === 0
    ) {
      this.monthList[1] = 29
    } else {
      this.monthList[1] = 28
    }
    // 获得指定年月的1号是星期几
    const firstDay = this.getWeekDay(this.year, this.month, 1)

    // 在1号前面填充多少个上个月的日期
    this.weekDay = firstDay === 7 ? 0 : firstDay
    // 获得最后一天是星期几,往后填充多少个
    const remineDay = this.getWeekDay(
      this.year,
      this.month,
      this.monthList[this.month - 1]
    )
    this.lastWeekDay = remineDay === 7 ? 6 : 6 - remineDay

    // 获得指定年月日是星期几
    this.currentWeek = this.getWeekDay(this.year, this.month, this.day)
 }

// 根据年月日获得为星期几
  getWeekDay(year: number, month: number, day: number) {
    return new Date(`${year}/${month}/${day}`).getDay()
  }

简而言之,只要你想方设法将preMonthSize,weekDay, month, lastWeekDay这几个变量根据年月日计算出来,页面就可以渲染出来。

详细的代码地址:https://github.com/zhangsundf/vue-canlendar/blob/master/canlendar.vue

### 使用 Electron 和 Vue 构建日历组件或应用 构建一个基于 Electron 和 Vue 的 MAC 版本的日历应用涉及多个技术栈的集成,包括前端框架 Vue、桌面端工具 Electron 以及界面设计库 Naive UI 或其他第三方库。 #### 1. 初始化项目 为了快速搭建基础环境,可以利用 `electron-forge` 工具初始化项目结构。执行以下命令创建一个新的项目并设置初始配置: ```bash npm init electron-app calendar-app --template=vue-essentials cd calendar-app ``` 此操作会生成一个带有基本 Vue 配置的 Electron 项目模板[^3]。 #### 2. 安装依赖项 安装必要的依赖包以支持项目的运行和开发。例如,对于界面部分可以选择使用 Naive UI 来替代默认样式库: ```bash npm install naive-ui dayjs ``` 这里引入了 `naive-ui` 提供现代化的设计风格,并借助 `dayjs` 处理日期逻辑[^1]。 #### 3. 创建路由系统 (可选) 如果计划扩展更多功能模块,则推荐加入 Vue Router 支持多页面导航能力。按照官方文档指引添加插件到工程里即可实现路径换效果: ```javascript // main.js 中注册 router 实例 import { createRouter, createWebHistory } from 'vue-router'; const routes = [ { path: '/', name: 'Home', component: () => import('@/views/Home.vue') }, // 添加额外视图... ]; export default createRouter({ history:createWebHistory(), routes, }); ``` #### 4. 开发核心业务逻辑 - 日历展示 编写具体的日历渲染方法,在 Home 组件内部定义数据模型与计算属性用于动态更新显示内容: ```html <template> <div class="calendar-container"> <n-calendar v-model:date-value="currentDate"/> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue' import { NCalendar } from 'naive-ui' export default defineComponent({ name:'HomePage', components:{NCalendar}, setup(){ let currentDate =ref(new Date()); return{currentDate}; } }) </script> <style scoped> .calendar-container{ width:80%; margin:auto; padding-top:50px; border-radius:10px; box-shadow:rgba(99,99,99,.2) 0 2px 8px 0; background-color:#fff; } </style> ``` 上述代码片段展示了如何结合 Naive UI 的 `<n-calendar>` 控件完成初步布局工作。 #### 5. 打包发布流程 当全部功能完成后就可以准备分发给最终用户啦! 运行下面这条指令将会自动生成适合目标平台的应用程序文件夹[^2]: ```bash npm run electron:build ``` --- ###
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值