移动端Vant中的Calendar日历增加显示农历(节日、节气)功能

核心: 使用 js-calendar-converter 库实现

npm地址:js-calendar-converter

内部使用原生calendar.js, 中国农历(阴阳历)和西元阳历即公历互转JavaScript库,具体实现感兴趣的可自行查看其实现源码。

原日历效果图:
无农历日历

更改后日历效果图:

农历日历
核心代码如下:

在main.js文件中引入js-calendar-converter,并挂在到Vue上,代码如下:

// vant 日历显示农历
import calendar from 'js-calendar-converter';
Vue.prototype.$calendar = calendar;

组件代码:

<van-calendar
  type="range"
  v-model="dateRangeShow"
  :default-date="dateRange"
  :min-date="minDate"
  :max-date="maxDate"
  :formatter="formatterCode"
  :poppable="false"
  color="#2873eb"
  :show-title="false"
  :allow-same-day="true"
  @confirm="onConfirm"
/>

js代码(代码里禁用日期功能和农历显示无关,可根据需求自行决策是否需要):

formatterCode(day) {
  const _time = new Date(day.date);

  // 禁用日期
  const times = _time.getTime();
  const cur = new Date().getTime();
  if (times > cur) {
    day.type = 'disabled';
  }

  const y = _time.getFullYear();
  const m = _time.getMonth() + 1;
  const d = _time.getDate(); // 从 Date 对象返回一个月中的某一天 (1 ~ 31)
  const info = this.$calendar.solar2lunar(y, m, d); // $calendar 已在全局注册绑定

  //   优先级:节日>节气>农历
  if (info.festival != null && info.festival != '') {
    day.bottomInfo = info.festival;
    day.className = 'festival'; //添加颜色样式
  } else if (info.Term != null && info.Term != '') {
    day.bottomInfo = info.Term;
    day.className = 'term'; //添加颜色样式
  } else if (info.IDayCn != null && info.IDayCn != '') {
    day.bottomInfo = info.IDayCn;
  }

  return day;
}

css代码(样式也可以根据自己需求进行自定义样式):

// 日历农历周末显示样式
.festival > div.van-calendar__bottom-info,
.term > div.van-calendar__bottom-info{
  color: #c80000;
}

拓展:web端ElementUI中的 DatePicker 日期选择器增加农历显示功能

使用 vue-jlunar-datepicker 依赖插件实现即可,具体样式可以自己根据需求进行修改处理。

代码简示:

// 日期控件替换为带农历的日期控件
import JDatePicker from "vue-jlunar-datepicker";
Vue.component("j-date-picker", JDatePicker);
<j-date-picker
	v-model="dayDate"
	type="date"
	placeholder="选择日期"
	show-lunar-class="FULLLUNAR"
	:show-lunar-control="true"
	:show-back-years="2"
	:show-lunar-icon="true"
	format="yyyy-MM-dd"
	:picker-options="pickerOptions"
	:clearable="false"
	style="width:100%;"
/>

相关学习资料地址:vue-jlunar-datepicker插件npm地址

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值