You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

896 lines
28 KiB

  1. <template>
  2. <u-popup
  3. :show="show"
  4. mode="bottom"
  5. :overlay="overlay"
  6. :duration="duration"
  7. :overlayStyle="overlayStyle"
  8. :overlayOpacity="overlayOpacity"
  9. :zIndex="zIndex"
  10. :safeAreaInsetBottom="safeAreaInsetBottom"
  11. :safeAreaInsetTop="safeAreaInsetTop"
  12. :bgColor="bgColor"
  13. :closeable="!pageInline"
  14. @close="close"
  15. :round="round"
  16. :pageInline="pageInline"
  17. :closeOnClickOverlay="closeOnClickOverlay"
  18. >
  19. <view class="u-calendar">
  20. <uHeader
  21. :title="title"
  22. :subtitle="subtitle"
  23. :showSubtitle="showSubtitle"
  24. :showTitle="showTitle"
  25. :weekText="weekText"
  26. :showSwitch="monthSwitch"
  27. :showToday="showToday"
  28. :todayText="todayText"
  29. :todayDisabled="todayDisabled"
  30. :prevDisabled="switchPrevDisabled"
  31. :nextDisabled="switchNextDisabled"
  32. :prevYearDisabled="switchPrevYearDisabled"
  33. :nextYearDisabled="switchNextYearDisabled"
  34. @prev="prevMonth"
  35. @next="nextMonth"
  36. @prevYear="prevYear"
  37. @nextYear="nextYear"
  38. @today="jumpToToday"
  39. ></uHeader>
  40. <view v-if="showTimePanel" class="u-calendar__time-panel">
  41. <view v-if="mode === 'single'" class="u-calendar__time-row">
  42. <text class="u-calendar__time-date">{{ singleDateLabel }}</text>
  43. <view class="u-calendar__time-trigger" @click="openTimePicker('single')">
  44. <text class="u-calendar__time-text">{{ singleTime }}</text>
  45. </view>
  46. </view>
  47. <view v-else-if="mode === 'range' && rangeResultMode === 'boundary'">
  48. <view class="u-calendar__time-row">
  49. <text class="u-calendar__time-date">{{ rangeStartDateLabel }}</text>
  50. <view class="u-calendar__time-trigger" @click="openTimePicker('start')">
  51. <text class="u-calendar__time-text">{{ rangeStartTime }}</text>
  52. </view>
  53. </view>
  54. <view class="u-calendar__time-row">
  55. <text class="u-calendar__time-date">{{ rangeEndDateLabel }}</text>
  56. <view class="u-calendar__time-trigger" @click="openTimePicker('end')">
  57. <text class="u-calendar__time-text">{{ rangeEndTime }}</text>
  58. </view>
  59. </view>
  60. </view>
  61. </view>
  62. <scroll-view
  63. v-if="!monthSwitch"
  64. :style="{
  65. height: addUnit(listHeight, 'px')
  66. }"
  67. scroll-y
  68. @scroll="onScroll"
  69. :scroll-top="scrollTop"
  70. :scrollIntoView="scrollIntoView"
  71. >
  72. <uMonth
  73. :color="color"
  74. :rowHeight="rowHeight"
  75. :showMark="showMark"
  76. :months="months"
  77. :mode="mode"
  78. :maxCount="maxCount"
  79. :startText="startText"
  80. :endText="endText"
  81. :defaultDate="defaultDate"
  82. :minDate="innerMinDate"
  83. :maxDate="innerMaxDate"
  84. :maxMonth="monthNum"
  85. :readonly="readonly"
  86. :maxRange="maxRange"
  87. :rangePrompt="rangePrompt"
  88. :showRangePrompt="showRangePrompt"
  89. :allowSameDay="allowSameDay"
  90. :forbidDays="forbidDays"
  91. :forbidDaysToast="forbidDaysToast"
  92. :monthFormat="monthFormat"
  93. :todayDate="todayDate"
  94. :todayColor="todayColor"
  95. ref="month"
  96. @monthSelected="monthSelected"
  97. @updateMonthTop="onUpdateMonthTop"
  98. ></uMonth>
  99. </scroll-view>
  100. <view
  101. v-else
  102. :style="{
  103. height: addUnit(listHeight, 'px')
  104. }"
  105. >
  106. <uMonth
  107. :color="color"
  108. :rowHeight="rowHeight"
  109. :showMark="showMark"
  110. :months="currentMonths"
  111. :mode="mode"
  112. :maxCount="maxCount"
  113. :startText="startText"
  114. :endText="endText"
  115. :defaultDate="defaultDate"
  116. :minDate="innerMinDate"
  117. :maxDate="innerMaxDate"
  118. :maxMonth="monthNum"
  119. :readonly="readonly"
  120. :maxRange="maxRange"
  121. :rangePrompt="rangePrompt"
  122. :showRangePrompt="showRangePrompt"
  123. :allowSameDay="allowSameDay"
  124. :forbidDays="forbidDays"
  125. :forbidDaysToast="forbidDaysToast"
  126. :monthFormat="monthFormat"
  127. :todayDate="todayDate"
  128. :todayColor="todayColor"
  129. ref="month"
  130. @monthSelected="monthSelected"
  131. @updateMonthTop="onUpdateMonthTop"
  132. ></uMonth>
  133. </view>
  134. <slot name="footer" v-if="showConfirm">
  135. <view class="u-calendar__confirm">
  136. <u-button
  137. shape="circle"
  138. :text="
  139. buttonDisabled ? confirmDisabledText : confirmText
  140. "
  141. :color="color"
  142. @click="confirm"
  143. :disabled="buttonDisabled"
  144. ></u-button>
  145. </view>
  146. </slot>
  147. </view>
  148. </u-popup>
  149. <u-popup
  150. :show="timePickerShow"
  151. mode="center"
  152. :round="8"
  153. :closeOnClickOverlay="true"
  154. @close="closeTimePicker"
  155. >
  156. <view class="u-calendar__time-picker">
  157. <view class="u-calendar__time-picker__header">
  158. <text class="u-calendar__time-picker__cancel" @click="closeTimePicker">取消</text>
  159. <text class="u-calendar__time-picker__title">选择时间</text>
  160. <text class="u-calendar__time-picker__confirm" @click="confirmTimePicker">确定</text>
  161. </view>
  162. <picker-view class="u-calendar__time-picker__body" :value="timePickerValue" @change="onTimePickerChange">
  163. <picker-view-column>
  164. <view v-for="(item, index) in hourOptions" :key="`h-${index}`" class="u-calendar__time-picker__item">{{ item }}</view>
  165. </picker-view-column>
  166. <picker-view-column v-if="timePrecision !== 'hour'">
  167. <view v-for="(item, index) in minuteOptions" :key="`m-${index}`" class="u-calendar__time-picker__item">{{ item }}</view>
  168. </picker-view-column>
  169. <picker-view-column v-if="timePrecision === 'second'">
  170. <view v-for="(item, index) in secondOptions" :key="`s-${index}`" class="u-calendar__time-picker__item">{{ item }}</view>
  171. </picker-view-column>
  172. </picker-view>
  173. </view>
  174. </u-popup>
  175. </template>
  176. <script>
  177. import uHeader from './header.vue'
  178. import uMonth from './month.vue'
  179. import { props } from './props.js'
  180. import util from './util.js'
  181. import dayjs from '../u-datetime-picker/dayjs.esm.min.js';
  182. import Calendar from '../../libs/util/calendar.js'
  183. import { mpMixin } from '../../libs/mixin/mpMixin.js'
  184. import { mixin } from '../../libs/mixin/mixin.js'
  185. import { addUnit, getPx, range, error, padZero } from '../../libs/function/index';
  186. import test from '../../libs/function/test';
  187. import { t } from '../../libs/i18n'
  188. /**
  189. * Calendar 日历
  190. * @description 此组件用于单个选择日期,范围选择日期等,日历被包裹在底部弹起的容器中.
  191. * @tutorial https://uview-plus.jiangruyi.com/components/calendar.html
  192. *
  193. * @property {String} title 标题内容 (默认 日期选择 )
  194. * @property {Boolean} showTitle 是否显示标题 (默认 true )
  195. * @property {Boolean} showSubtitle 是否显示副标题 (默认 true )
  196. * @property {String} mode 日期类型选择 single-选择单个日期,multiple-可以选择多个日期,range-选择日期范围 ( 默认 'single' )
  197. * @property {String} startText mode=range时,第一个日期底部的提示文字 (默认 '开始' )
  198. * @property {String} endText mode=range时,最后一个日期底部的提示文字 (默认 '结束' )
  199. * @property {Array} customList 自定义列表
  200. * @property {String} color 主题色,对底部按钮和选中日期有效 (默认 ‘#3c9cff' )
  201. * @property {String | Number} minDate 最小的可选日期 (默认 0 )
  202. * @property {String | Number} maxDate 最大可选日期 (默认 0 )
  203. * @property {Array | String| Date} defaultDate 默认选中的日期,mode为multiple或range是必须为数组格式
  204. * @property {String | Number} maxCount mode=multiple时,最多可选多少个日期 (默认 Number.MAX_SAFE_INTEGER )
  205. * @property {String | Number} rowHeight 日期行高 (默认 56 )
  206. * @property {Function} formatter 日期格式化函数
  207. * @property {Boolean} showLunar 是否显示农历 (默认 false )
  208. * @property {Boolean} showMark 是否显示月份背景色 (默认 true )
  209. * @property {String} confirmText 确定按钮的文字 (默认 '确定' )
  210. * @property {String} confirmDisabledText 确认按钮处于禁用状态时的文字 (默认 '确定' )
  211. * @property {Boolean} show 是否显示日历弹窗 (默认 false )
  212. * @property {Boolean} overlay 是否显示遮罩 (默认 true )
  213. * @property {String | Number} duration 动画时长,单位ms (默认 300 )
  214. * @property {Object | String} overlayStyle 自定义遮罩的样式
  215. * @property {Number | String} overlayOpacity 遮罩透明度,0-1之间 (默认 0.5 )
  216. * @property {String | Number} zIndex 弹出层的z-index值 (默认 10075 )
  217. * @property {Boolean} safeAreaInsetBottom 是否留出底部安全距离 (默认 true )
  218. * @property {Boolean} safeAreaInsetTop 是否留出顶部安全距离(状态栏高度) (默认 false )
  219. * @property {String} bgColor 弹窗背景色,设置为transparent可去除白色背景
  220. * @property {Boolean} closeOnClickOverlay 是否允许点击遮罩关闭日历 (默认 false )
  221. * @property {Boolean} readonly 是否为只读状态,只读状态下禁止选择日期 (默认 false )
  222. * @property {String | Number} maxRange 日期区间最多可选天数,默认无限制,mode = range时有效
  223. * @property {String} rangePrompt 范围选择超过最多可选天数时的提示文案,mode = range时有效
  224. * @property {Boolean} showRangePrompt 范围选择超过最多可选天数时,是否展示提示文案,mode = range时有效 (默认 true )
  225. * @property {Boolean} allowSameDay 是否允许日期范围的起止时间为同一天,mode = range时有效 (默认 false )
  226. * @property {String} rangeResultMode 区间模式下确认返回值格式,all-返回区间内所有日期,boundary-仅返回起止日期 (默认 'all' )
  227. * @property {Boolean} enableTime 是否开启时分秒选择 (默认 false )
  228. * @property {String} timePrecision 时间精度,hour-仅时,minute-时分,second-时分秒 (默认 'minute' )
  229. * @property {String} defaultTime 默认时间,支持HH/HH:mm/HH:mm:ss,不传则按00:00补齐
  230. * @property {Number|String} round 圆角值,默认无圆角 (默认 0 )
  231. * @property {Number|String} monthNum 最多展示的月份数量 (默认 3 )
  232. * @property {Boolean} monthSwitch 是否启用非滚动的单月切换模式 (默认 false )
  233. * @property {String} todayColor 今天日期的独立高亮颜色,默认跟随主题色
  234. * @property {Array} weekText 星期文案 (默认 ['一', '二', '三', '四', '五', '六', '日'] )
  235. *
  236. * @event {Function()} confirm 点击确定按钮时触发 选择日期相关的返回参数
  237. * @event {Function()} close 日历关闭时触发 可定义页面关闭时的回调事件
  238. * @example <u-calendar :defaultDate="defaultDateMultiple" :show="show" mode="multiple" @confirm="confirm">
  239. </u-calendar>
  240. * */
  241. export default {
  242. name: 'u-calendar',
  243. mixins: [mpMixin, mixin, props],
  244. components: {
  245. uHeader,
  246. uMonth
  247. },
  248. data() {
  249. return {
  250. // 需要显示的月份的数组
  251. months: [],
  252. // 在月份滚动区域中,当前视图中月份的index索引
  253. monthIndex: 0,
  254. // 月份滚动区域的高度
  255. listHeight: 0,
  256. // month组件中选择的日期数组
  257. selected: [],
  258. scrollIntoView: '',
  259. scrollIntoViewScroll: '',
  260. scrollTop:0,
  261. timePickerShow: false,
  262. timePickerTarget: 'single',
  263. timePickerValue: [0, 0, 0],
  264. hourOptions: [],
  265. minuteOptions: [],
  266. secondOptions: [],
  267. singleTime: '00:00',
  268. rangeStartTime: '00:00',
  269. rangeEndTime: '00:00',
  270. // 过滤处理方法
  271. innerFormatter: (value) => value
  272. }
  273. },
  274. watch: {
  275. scrollIntoView: {
  276. immediate: true,
  277. handler(n) {
  278. // console.log('scrollIntoView', n)
  279. }
  280. },
  281. selectedChange: {
  282. immediate: true,
  283. handler(n) {
  284. this.setMonth()
  285. }
  286. },
  287. timePrecision() {
  288. this.initTimeOptions()
  289. this.initTimeValues()
  290. },
  291. defaultTime() {
  292. this.initTimeValues()
  293. },
  294. // 打开弹窗时,设置月份数据
  295. show: {
  296. immediate: true,
  297. handler(n) {
  298. if (n) {
  299. this.setMonth()
  300. } else {
  301. // 关闭时重置scrollIntoView,否则会出现二次打开日历,当前月份数据显示不正确。
  302. // scrollIntoView需要有一个值变动过程,才会产生作用。
  303. this.scrollIntoView = ''
  304. }
  305. }
  306. }
  307. },
  308. computed: {
  309. // 由于maxDate和minDate可以为字符串(2021-10-10),或者数值(时间戳),但是dayjs如果接受字符串形式的时间戳会有问题,这里进行处理
  310. innerMaxDate() {
  311. return test.number(this.maxDate)
  312. ? Number(this.maxDate)
  313. : this.maxDate
  314. },
  315. innerMinDate() {
  316. return test.number(this.minDate)
  317. ? Number(this.minDate)
  318. : this.minDate
  319. },
  320. todayDate() {
  321. return dayjs().format('YYYY-MM-DD')
  322. },
  323. todayText() {
  324. return t('up.calendar.today')
  325. },
  326. todayDisabled() {
  327. const today = dayjs(this.todayDate)
  328. const minDate = this.innerMinDate
  329. ? dayjs(this.innerMinDate)
  330. : null
  331. const maxDate = this.innerMaxDate
  332. ? dayjs(this.innerMaxDate)
  333. : null
  334. if (minDate && today.isBefore(minDate, 'day')) {
  335. return true
  336. }
  337. if (maxDate && today.isAfter(maxDate, 'day')) {
  338. return true
  339. }
  340. return false
  341. },
  342. // 多个条件的变化,会引起选中日期的变化,这里统一管理监听
  343. selectedChange() {
  344. return [this.innerMinDate, this.innerMaxDate, this.defaultDate]
  345. },
  346. subtitle() {
  347. // 初始化时,this.months为空数组,所以需要特别判断处理
  348. if (this.months.length) {
  349. if (uni.getLocale() == 'zh-Hans' || uni.getLocale() == 'zh-Hant') {
  350. return this.months[this.monthIndex].year + '年' + (this.months[this.monthIndex].month < 10 ? '0' + this.months[this.monthIndex].month : this.months[this.monthIndex].month) + '月'
  351. } else {
  352. return (this.months[this.monthIndex].month < 10 ? '0' + this.months[this.monthIndex].month : this.months[this.monthIndex].month) + '/' + this.months[this.monthIndex].year
  353. }
  354. } else {
  355. return ''
  356. }
  357. },
  358. currentMonths() {
  359. if (this.monthSwitch && this.months.length) {
  360. return [this.months[this.monthIndex]]
  361. }
  362. return this.months
  363. },
  364. switchPrevDisabled() {
  365. return this.monthIndex <= 0
  366. },
  367. switchNextDisabled() {
  368. return this.monthIndex >= this.months.length - 1
  369. },
  370. switchPrevYearDisabled() {
  371. return this.monthIndex - 12 < 0
  372. },
  373. switchNextYearDisabled() {
  374. return this.monthIndex + 12 > this.months.length - 1
  375. },
  376. showTimePanel() {
  377. if (!this.enableTime) return false
  378. if (this.mode === 'single') return true
  379. if (this.mode === 'range' && this.rangeResultMode === 'boundary') {
  380. return true
  381. }
  382. return false
  383. },
  384. singleDateLabel() {
  385. return this.selected[0] || '--'
  386. },
  387. rangeStartDateLabel() {
  388. return this.selected[0] || '--'
  389. },
  390. rangeEndDateLabel() {
  391. if (this.selected.length >= 2) {
  392. return this.selected[this.selected.length - 1]
  393. }
  394. return '--'
  395. },
  396. buttonDisabled() {
  397. // 如果为range类型,且选择的日期个数不足1个时,让底部的按钮出于disabled状态
  398. if (this.mode === 'range') {
  399. if (this.selected.length <= 1) {
  400. return true
  401. } else {
  402. return false
  403. }
  404. } else {
  405. return false
  406. }
  407. }
  408. },
  409. mounted() {
  410. this.start = Date.now()
  411. this.init()
  412. },
  413. emits: ["confirm", "close"],
  414. methods: {
  415. addUnit,
  416. padTime(num) {
  417. return String(num).padStart(2, '0')
  418. },
  419. initTimeOptions() {
  420. this.hourOptions = Array.from({ length: 24 }, (_, i) => this.padTime(i))
  421. this.minuteOptions = Array.from({ length: 60 }, (_, i) => this.padTime(i))
  422. this.secondOptions = Array.from({ length: 60 }, (_, i) => this.padTime(i))
  423. },
  424. parseTimeValue(value = '') {
  425. const raw = String(value || '').trim()
  426. const parts = raw.length ? raw.split(':') : []
  427. const getNumber = (index, max) => {
  428. const current = Number(parts[index] || 0)
  429. if (Number.isNaN(current)) return 0
  430. return Math.max(0, Math.min(max, current))
  431. }
  432. const hour = getNumber(0, 23)
  433. const minute = getNumber(1, 59)
  434. const second = getNumber(2, 59)
  435. return [hour, minute, second]
  436. },
  437. getDefaultTimeValue() {
  438. const [hour, minute, second] = this.parseTimeValue(this.defaultTime)
  439. if (this.timePrecision === 'hour') {
  440. return this.padTime(hour)
  441. }
  442. if (this.timePrecision === 'second') {
  443. return `${this.padTime(hour)}:${this.padTime(minute)}:${this.padTime(second)}`
  444. }
  445. return `${this.padTime(hour)}:${this.padTime(minute)}`
  446. },
  447. initTimeValues() {
  448. const value = this.getDefaultTimeValue()
  449. this.singleTime = value
  450. this.rangeStartTime = value
  451. this.rangeEndTime = value
  452. },
  453. timeToPickerValue(value = '') {
  454. const [hour, minute, second] = this.parseTimeValue(value)
  455. return [hour, minute, second]
  456. },
  457. pickerValueToTime(value = []) {
  458. const hour = Number(value[0] || 0)
  459. const minute = Number(value[1] || 0)
  460. const second = Number(value[2] || 0)
  461. if (this.timePrecision === 'hour') {
  462. return this.padTime(hour)
  463. }
  464. if (this.timePrecision === 'second') {
  465. return `${this.padTime(hour)}:${this.padTime(minute)}:${this.padTime(second)}`
  466. }
  467. return `${this.padTime(hour)}:${this.padTime(minute)}`
  468. },
  469. openTimePicker(target) {
  470. this.timePickerTarget = target
  471. let currentValue = this.singleTime
  472. if (target === 'start') currentValue = this.rangeStartTime
  473. if (target === 'end') currentValue = this.rangeEndTime
  474. this.timePickerValue = this.timeToPickerValue(currentValue)
  475. this.timePickerShow = true
  476. },
  477. onTimePickerChange(e) {
  478. this.timePickerValue = e.detail.value
  479. },
  480. closeTimePicker() {
  481. this.timePickerShow = false
  482. },
  483. confirmTimePicker() {
  484. const value = this.pickerValueToTime(this.timePickerValue)
  485. if (this.timePickerTarget === 'single') this.singleTime = value
  486. if (this.timePickerTarget === 'start') this.rangeStartTime = value
  487. if (this.timePickerTarget === 'end') this.rangeEndTime = value
  488. this.timePickerShow = false
  489. },
  490. timeToSecond(timeText = '') {
  491. const [hour, minute, second] = this.parseTimeValue(timeText)
  492. return hour * 3600 + minute * 60 + second
  493. },
  494. validateSameDayRangeTime() {
  495. if (!this.enableTime || this.mode !== 'range' || this.rangeResultMode !== 'boundary') {
  496. return true
  497. }
  498. if (this.selected.length < 2) return true
  499. const startDate = this.selected[0]
  500. const endDate = this.selected[this.selected.length - 1]
  501. if (startDate !== endDate) return true
  502. const startSeconds = this.timeToSecond(this.rangeStartTime)
  503. const endSeconds = this.timeToSecond(this.rangeEndTime)
  504. if (endSeconds < startSeconds) {
  505. uni.showToast({
  506. title: '结束时间不能早于开始时间',
  507. icon: 'none'
  508. })
  509. return false
  510. }
  511. return true
  512. },
  513. appendTime(dateText, timeText) {
  514. return `${dateText} ${timeText}`
  515. },
  516. getConfirmValue(selected = this.selected) {
  517. let result = selected
  518. if (
  519. this.mode === 'range' &&
  520. this.rangeResultMode === 'boundary' &&
  521. selected.length >= 2
  522. ) {
  523. const len = selected.length - 1
  524. result = [selected[0], selected[len]]
  525. }
  526. if (!this.showTimePanel || !this.enableTime) {
  527. return result
  528. }
  529. if (this.mode === 'single' && result.length >= 1) {
  530. return [this.appendTime(result[0], this.singleTime)]
  531. }
  532. if (this.mode === 'range' && this.rangeResultMode === 'boundary' && result.length >= 2) {
  533. return [
  534. this.appendTime(result[0], this.rangeStartTime),
  535. this.appendTime(result[1], this.rangeEndTime)
  536. ]
  537. }
  538. return result
  539. },
  540. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  541. setFormatter(e) {
  542. this.innerFormatter = e
  543. },
  544. // month组件内部选择日期后,通过事件通知给父组件
  545. monthSelected(e,scene ='init') {
  546. this.selected = e
  547. if (!this.showConfirm) {
  548. // 在不需要确认按钮的情况下,如果为单选,或者范围多选且已选长度大于2,则直接进行返还
  549. if (
  550. this.mode === 'multiple' ||
  551. this.mode === 'single' ||
  552. (this.mode === 'range' && this.selected.length >= 2)
  553. ) {
  554. if( scene === 'init'){
  555. return
  556. }
  557. if( scene === 'tap') {
  558. if (!this.validateSameDayRangeTime()) return
  559. this.$emit('confirm', this.getConfirmValue())
  560. }
  561. }
  562. }
  563. },
  564. init() {
  565. // 校验maxDate,不能小于minDate。
  566. if (
  567. this.innerMaxDate &&
  568. this.innerMinDate &&
  569. new Date(this.innerMaxDate).getTime() < new Date(this.innerMinDate).getTime()
  570. ) {
  571. return error('maxDate不能小于minDate时间')
  572. }
  573. // 滚动区域的高度
  574. let bottomPadding = 0;
  575. if (this.pageInline) {
  576. bottomPadding = 0
  577. } else {
  578. bottomPadding = 30
  579. }
  580. this.listHeight = this.rowHeight * (this.monthSwitch ? 6 : 5) + bottomPadding
  581. this.initTimeOptions()
  582. this.initTimeValues()
  583. this.setMonth()
  584. },
  585. close() {
  586. this.$emit('close')
  587. },
  588. // 点击确定按钮
  589. confirm() {
  590. if (!this.buttonDisabled) {
  591. if (!this.validateSameDayRangeTime()) return
  592. this.$emit('confirm', this.getConfirmValue())
  593. }
  594. },
  595. // 获得两个日期之间的月份数
  596. getMonths(minDate, maxDate) {
  597. const minYear = dayjs(minDate).year()
  598. const minMonth = dayjs(minDate).month() + 1
  599. const maxYear = dayjs(maxDate).year()
  600. const maxMonth = dayjs(maxDate).month() + 1
  601. return (maxYear - minYear) * 12 + (maxMonth - minMonth) + 1
  602. },
  603. // 设置月份数据
  604. setMonth() {
  605. // 最小日期的毫秒数
  606. const minDate = this.innerMinDate || dayjs().valueOf()
  607. // 如果没有指定最大日期,则往后推3个月
  608. const maxDate =
  609. this.innerMaxDate ||
  610. dayjs(minDate)
  611. .add(this.monthNum - 1, 'month')
  612. .valueOf()
  613. // 最大最小月份之间的共有多少个月份,
  614. const months = range(
  615. 1,
  616. this.monthNum,
  617. this.getMonths(minDate, maxDate)
  618. )
  619. // 先清空数组
  620. this.months = []
  621. for (let i = 0; i < months; i++) {
  622. this.months.push({
  623. date: new Array(
  624. dayjs(minDate).add(i, 'month').daysInMonth()
  625. )
  626. .fill(1)
  627. .map((item, index) => {
  628. // 日期,取值1-31
  629. let day = index + 1
  630. // 星期,0-6,0为周日
  631. const week = dayjs(minDate)
  632. .add(i, 'month')
  633. .date(day)
  634. .day()
  635. const date = dayjs(minDate)
  636. .add(i, 'month')
  637. .date(day)
  638. .format('YYYY-MM-DD')
  639. let bottomInfo = ''
  640. if (this.showLunar) {
  641. // 将日期转为农历格式
  642. const lunar = Calendar.solar2lunar(
  643. dayjs(date).year(),
  644. dayjs(date).month() + 1,
  645. dayjs(date).date()
  646. )
  647. bottomInfo = lunar.IDayCn
  648. }
  649. let config = {
  650. day,
  651. week,
  652. // 小于最小允许的日期,或者大于最大的日期,则设置为disabled状态
  653. disabled:
  654. dayjs(date).isBefore(
  655. dayjs(minDate).format('YYYY-MM-DD')
  656. ) ||
  657. dayjs(date).isAfter(
  658. dayjs(maxDate).format('YYYY-MM-DD')
  659. ),
  660. // 返回一个日期对象,供外部的formatter获取当前日期的年月日等信息,进行加工处理
  661. date: new Date(date),
  662. bottomInfo,
  663. dot: false,
  664. month:
  665. dayjs(minDate).add(i, 'month').month() + 1
  666. }
  667. const formatter =
  668. this.formatter || this.innerFormatter
  669. return formatter(config)
  670. }),
  671. // 当前所属的月份
  672. month: dayjs(minDate).add(i, 'month').month() + 1,
  673. // 当前年份
  674. year: dayjs(minDate).add(i, 'month').year()
  675. })
  676. }
  677. if (this.monthSwitch) {
  678. this.monthIndex = this.getDefaultMonthIndex()
  679. }
  680. },
  681. getDefaultMonthIndex() {
  682. let selected = dayjs().format('YYYY-MM')
  683. if (this.defaultDate) {
  684. if (!test.array(this.defaultDate)) {
  685. selected = dayjs(this.defaultDate).format('YYYY-MM')
  686. } else if (this.defaultDate.length) {
  687. selected = dayjs(this.defaultDate[0]).format('YYYY-MM')
  688. }
  689. }
  690. const index = this.months.findIndex(({ year, month }) => {
  691. return `${year}-${padZero(month)}` === selected
  692. })
  693. return index === -1 ? 0 : index
  694. },
  695. prevMonth() {
  696. if (!this.switchPrevDisabled) {
  697. this.monthIndex -= 1
  698. }
  699. },
  700. nextMonth() {
  701. if (!this.switchNextDisabled) {
  702. this.monthIndex += 1
  703. }
  704. },
  705. prevYear() {
  706. if (!this.switchPrevYearDisabled) {
  707. this.monthIndex -= 12
  708. }
  709. },
  710. nextYear() {
  711. if (!this.switchNextYearDisabled) {
  712. this.monthIndex += 12
  713. }
  714. },
  715. jumpToToday() {
  716. if (this.todayDisabled) {
  717. return
  718. }
  719. const targetMonth = dayjs(this.todayDate).format('YYYY-MM')
  720. const selectToday = () => {
  721. if (this.mode === 'range') {
  722. return
  723. }
  724. this.$refs.month && this.$refs.month.selectDate(this.todayDate)
  725. }
  726. if (this.monthSwitch) {
  727. const todayMonthIndex = this.months.findIndex(({ year, month }) => {
  728. return `${year}-${padZero(month)}` === targetMonth
  729. })
  730. if (todayMonthIndex !== -1) {
  731. this.monthIndex = todayMonthIndex
  732. this.$nextTick(selectToday)
  733. }
  734. return
  735. }
  736. this.scrollIntoDefaultMonth(targetMonth)
  737. this.$nextTick(selectToday)
  738. },
  739. // 滚动到默认设置的月份
  740. scrollIntoDefaultMonth(selected) {
  741. // 查询默认日期在可选列表的下标
  742. const _index = this.months.findIndex(({
  743. year,
  744. month
  745. }) => {
  746. month = padZero(month)
  747. return `${year}-${month}` === selected
  748. })
  749. if (_index !== -1) {
  750. // #ifndef MP-WEIXIN
  751. this.$nextTick(() => {
  752. this.scrollIntoView = ''
  753. this.scrollIntoView = `month-${_index}`
  754. this.scrollIntoViewScroll = this.scrollIntoView
  755. })
  756. // #endif
  757. // #ifdef MP-WEIXIN
  758. this.scrollTop = this.months[_index].top || 0;
  759. // #endif
  760. }
  761. },
  762. // scroll-view滚动监听
  763. onScroll(event) {
  764. // 不允许小于0的滚动值,如果scroll-view到顶了,继续下拉,会出现负数值
  765. const scrollTop = Math.max(0, event.detail.scrollTop)
  766. // 将当前滚动条数值,除以滚动区域的高度,可以得出当前滚动到了哪一个月份的索引
  767. for (let i = 0; i < this.months.length; i++) {
  768. if (scrollTop >= (this.months[i].top || this.listHeight)) {
  769. this.monthIndex = i
  770. this.scrollIntoViewScroll = `month-${i}`
  771. }
  772. }
  773. },
  774. // 更新月份的top值
  775. onUpdateMonthTop(topArr = []) {
  776. if (this.monthSwitch) {
  777. return
  778. }
  779. this.updateMonthTop(topArr)
  780. },
  781. updateMonthTop(topArr = []) {
  782. // 设置对应月份的top值,用于onScroll方法更新月份
  783. topArr.map((item, index) => {
  784. this.months[index].top = item
  785. })
  786. // 获取默认日期的下标
  787. if (!this.defaultDate) {
  788. // 如果没有设置默认日期,则将当天日期设置为默认选中的日期
  789. const selected = dayjs().format("YYYY-MM")
  790. this.scrollIntoDefaultMonth(selected)
  791. return
  792. }
  793. let selected = dayjs().format("YYYY-MM");
  794. // 单选模式,可以是字符串或数组,Date对象等
  795. if (!test.array(this.defaultDate)) {
  796. selected = dayjs(this.defaultDate).format("YYYY-MM")
  797. } else {
  798. selected = dayjs(this.defaultDate[0]).format("YYYY-MM");
  799. }
  800. this.scrollIntoDefaultMonth(selected)
  801. }
  802. }
  803. }
  804. </script>
  805. <style lang="scss" scoped>
  806. .u-calendar {
  807. color: var(--up-main-color, $u-main-color);
  808. background-color: var(--up-card-bg-color, #ffffff);
  809. &__time-panel {
  810. padding: 8px 16px 0;
  811. }
  812. &__time-row {
  813. height: 34px;
  814. display: flex;
  815. align-items: center;
  816. justify-content: space-between;
  817. margin-bottom: 6px;
  818. }
  819. &__time-date {
  820. font-size: 13px;
  821. color: #303133;
  822. }
  823. &__time-trigger {
  824. min-width: 92px;
  825. height: 30px;
  826. padding: 0 10px;
  827. border-radius: 15px;
  828. border: 1px solid #dcdfe6;
  829. display: flex;
  830. align-items: center;
  831. justify-content: center;
  832. }
  833. &__time-text {
  834. font-size: 14px;
  835. color: #303133;
  836. }
  837. &__time-picker {
  838. width: 320px;
  839. background-color: #ffffff;
  840. border-radius: 8px;
  841. overflow: hidden;
  842. }
  843. &__time-picker__header {
  844. height: 44px;
  845. padding: 0 14px;
  846. display: flex;
  847. align-items: center;
  848. justify-content: space-between;
  849. border-bottom: 1px solid #f0f0f0;
  850. }
  851. &__time-picker__cancel {
  852. font-size: 14px;
  853. color: #909399;
  854. }
  855. &__time-picker__title {
  856. font-size: 15px;
  857. color: #303133;
  858. font-weight: 600;
  859. }
  860. &__time-picker__confirm {
  861. font-size: 14px;
  862. color: #3c9cff;
  863. }
  864. &__time-picker__body {
  865. width: 320px;
  866. height: 200px;
  867. }
  868. &__time-picker__item {
  869. height: 40px;
  870. line-height: 40px;
  871. text-align: center;
  872. font-size: 16px;
  873. color: #303133;
  874. }
  875. &__confirm {
  876. padding: 7px 18px;
  877. }
  878. }
  879. </style>