这是我参与更文挑战的第4天,活动详情查看: 更文挑战
农历功能
今天进入开发的第一个功能:「农历」,由于 MAC 自带的日历没有农历功能,在国内我们很多节日和亲朋好友的生日都是按农历来算得。所以农历功能是我自学开发日历的第一个出发点。
开始开发之前,必然还是需要全网搜一搜有没有可使用的第三方插件,果不其然 lunar-typescript
进入我的视线。
lunar-typescript
目前来说提供农历功能的第三方 TypeScript 插件中 lunar 是个人觉得写的最好的。
功能封装的很好,基本涵盖了我所需要的功能:
lunar 是一款无第三方依赖的公历(阳历)和农历(阴历、老黄历)工具,支持星座、儒略日、干支、生肖、节气、节日、彭祖百忌、每日宜忌、吉神宜趋、凶煞宜忌、吉神(喜神/福神/财神/阳贵神/阴贵神)方位、胎神方位、冲煞、纳音、星宿、八字、五行、十神、建除十二值星、青龙名堂等十二神、黄道黑道日及吉凶等。
具体可查看官方文档
使用方法也很简单:
// 安装
yarn add lunar-typescript
// 调用
import { Solar } from 'lunar-typescript';
const solar = Solar.fromYmd(1986, 5, 29);
console.log(solar.toFullString());
console.log(solar.getLunar().toFullString());
// 显示结果
1986-05-29 00:00:00 星期四 双子座
一九八六年四月廿一 丙寅(虎)年 癸巳(蛇)月 癸酉(鸡)日 子(鼠)时 纳音[炉中火 长流水 剑锋金 桑柘木] 星期四 北方玄武 星宿[斗木獬](吉) 彭祖百忌[癸不词讼理弱敌强 酉不会客醉坐颠狂] 喜神方位[巽](东南) 阳贵神方位[巽](东南) 阴贵神方位[震](正东) 福神方位[兑](正西) 财神方位[离](正南) 冲[(丁卯)兔] 煞[东]
为我所用
在本文中,主要把 lunar-typescript 封装成一个 Service 类:LunarService
import { Solar, Lunar } from 'lunar-typescript';
/**
* 显示日期相关功能
*/
export default class LunarService {
lunar: Lunar;
solar: Solar;
constructor(date: Date = new Date()) {
this.lunar = Lunar.fromDate(date);
this.solar = Solar.fromDate(date);
}
/**
* 包括:法定节日、农历等
* @returns 显示在界面上所有和节日有关的
*/
inDayCellContent(changeShowFestivals: boolean): string {
if (changeShowFestivals) {
const solarFestivals = this.solar.getFestivals();
if (solarFestivals.length > 0) {
return solarFestivals.join(' ');
}
const lunarFestivals = this.lunar.getFestivals();
if (lunarFestivals.length > 0) {
return lunarFestivals.join(' ');
}
}
return this.lunar.getJieQi() ||
`${this.lunar.getMonthInChinese()}月${this.lunar.getDayInChinese()}`;
}
}
代码很简单,就是根据输入不同的日期,显示出农历,如果需要显示节假日,则可以优先显示。
插入界面
正如 Electron+Vue3 MAC 版日历开发记录(3)——PrimeVue末尾留下的小尾巴,如何在日历使用 dayGridPlugin
直接使用 Month View
。
回到 FullcalendarSub.vue
组件中:
// config
views: this.dayCellNewContent(),
...
dayCellNewContent() {
const that = this;
return {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit'},
dayCellContent(item: any) {
const date = new Date(item.date);
const calendarViewService = new CalendarViewService();
return calendarViewService.showView(item.dayNumberText, date, that.changeShowFestivals, that.changeShowWeather, that.weather);
},
},
};
},
这里我把 view 也封装成 CalendarViewService
:
const lunarService = new LunarService(date);
const dayTextInChinese = lunarService.inDayCellContent(changeShowFestivals);
// 借助 FullCalendar 提供的 item 返回的每一格元素 Object
return {
html: `<div class="fc-daygrid-day-number">${dayNumberText}</div>
<div class="fc-daygrid-day-chinese">${dayTextInChinese}</div>`,
};
其中这里的 item Object 如下:
小结
效果图在开始的文章中有所体现,这里就不放出来了,具体代码也放在 Github 上 fanly/fanlymenu,欢迎查看!
最后感谢自己能坚持到第四天,也欢迎大家看看前三天的记录,对本项目有个初步的了解:
Electron+Vue3 MAC 版日历开发记录(1) Electron+Vue3 MAC 版日历开发记录(2)——功能清单 Electron+Vue3 MAC 版日历开发记录(3)——PrimeVue