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.

409 lines
13 KiB

2 months ago
  1. <template>
  2. <u-popup
  3. :show="show"
  4. mode="bottom"
  5. closeable
  6. @close="close"
  7. :round="round"
  8. :closeOnClickOverlay="closeOnClickOverlay"
  9. >
  10. <view class="u-calendar">
  11. <uHeader
  12. :title="title"
  13. :subtitle="subtitle"
  14. :showSubtitle="showSubtitle"
  15. :showTitle="showTitle"
  16. ></uHeader>
  17. <scroll-view
  18. :style="{
  19. height: addUnit(listHeight)
  20. }"
  21. scroll-y
  22. @scroll="onScroll"
  23. :scroll-top="scrollTop"
  24. :scrollIntoView="scrollIntoView"
  25. >
  26. <uMonth
  27. :color="color"
  28. :rowHeight="rowHeight"
  29. :showMark="showMark"
  30. :months="months"
  31. :mode="mode"
  32. :maxCount="maxCount"
  33. :startText="startText"
  34. :endText="endText"
  35. :defaultDate="defaultDate"
  36. :minDate="innerMinDate"
  37. :maxDate="innerMaxDate"
  38. :maxMonth="monthNum"
  39. :readonly="readonly"
  40. :maxRange="maxRange"
  41. :rangePrompt="rangePrompt"
  42. :showRangePrompt="showRangePrompt"
  43. :allowSameDay="allowSameDay"
  44. ref="month"
  45. @monthSelected="monthSelected"
  46. @updateMonthTop="updateMonthTop"
  47. ></uMonth>
  48. </scroll-view>
  49. <slot name="footer" v-if="showConfirm">
  50. <view class="u-calendar__confirm">
  51. <u-button
  52. shape="circle"
  53. :text="
  54. buttonDisabled ? confirmDisabledText : confirmText
  55. "
  56. :color="color"
  57. @click="confirm"
  58. :disabled="buttonDisabled"
  59. ></u-button>
  60. </view>
  61. </slot>
  62. </view>
  63. </u-popup>
  64. </template>
  65. <script>
  66. import uHeader from './header.vue'
  67. import uMonth from './month.vue'
  68. import { props } from './props.js'
  69. import util from './util.js'
  70. import dayjs from 'dayjs/esm/index'
  71. import Calendar from '../../libs/util/calendar.js'
  72. import { mpMixin } from '../../libs/mixin/mpMixin.js'
  73. import { mixin } from '../../libs/mixin/mixin.js'
  74. import { addUnit, range, error, padZero } from '../../libs/function/index';
  75. import test from '../../libs/function/test';
  76. /**
  77. * Calendar 日历
  78. * @description 此组件用于单个选择日期范围选择日期等日历被包裹在底部弹起的容器中.
  79. * @tutorial https://ijry.github.io/uview-plus/components/calendar.html
  80. *
  81. * @property {String} title 标题内容 (默认 日期选择 )
  82. * @property {Boolean} showTitle 是否显示标题 (默认 true )
  83. * @property {Boolean} showSubtitle 是否显示副标题 (默认 true )
  84. * @property {String} mode 日期类型选择 single-选择单个日期multiple-可以选择多个日期range-选择日期范围 默认 'single' )
  85. * @property {String} startText mode=range时第一个日期底部的提示文字 (默认 '开始' )
  86. * @property {String} endText mode=range时最后一个日期底部的提示文字 (默认 '结束' )
  87. * @property {Array} customList 自定义列表
  88. * @property {String} color 主题色对底部按钮和选中日期有效 (默认 #3c9cff' )
  89. * @property {String | Number} minDate 最小的可选日期 (默认 0 )
  90. * @property {String | Number} maxDate 最大可选日期 (默认 0 )
  91. * @property {Array | String| Date} defaultDate 默认选中的日期mode为multiple或range是必须为数组格式
  92. * @property {String | Number} maxCount mode=multiple时最多可选多少个日期 (默认 Number.MAX_SAFE_INTEGER )
  93. * @property {String | Number} rowHeight 日期行高 (默认 56 )
  94. * @property {Function} formatter 日期格式化函数
  95. * @property {Boolean} showLunar 是否显示农历 (默认 false )
  96. * @property {Boolean} showMark 是否显示月份背景色 (默认 true )
  97. * @property {String} confirmText 确定按钮的文字 (默认 '确定' )
  98. * @property {String} confirmDisabledText 确认按钮处于禁用状态时的文字 (默认 '确定' )
  99. * @property {Boolean} show 是否显示日历弹窗 (默认 false )
  100. * @property {Boolean} closeOnClickOverlay 是否允许点击遮罩关闭日历 (默认 false )
  101. * @property {Boolean} readonly 是否为只读状态只读状态下禁止选择日期 (默认 false )
  102. * @property {String | Number} maxRange 日期区间最多可选天数默认无限制mode = range时有效
  103. * @property {String} rangePrompt 范围选择超过最多可选天数时的提示文案mode = range时有效
  104. * @property {Boolean} showRangePrompt 范围选择超过最多可选天数时是否展示提示文案mode = range时有效 (默认 true )
  105. * @property {Boolean} allowSameDay 是否允许日期范围的起止时间为同一天mode = range时有效 (默认 false )
  106. * @property {Number|String} round 圆角值默认无圆角 (默认 0 )
  107. * @property {Number|String} monthNum 最多展示的月份数量 (默认 3 )
  108. *
  109. * @event {Function()} confirm 点击确定按钮时触发 选择日期相关的返回参数
  110. * @event {Function()} close 日历关闭时触发 可定义页面关闭时的回调事件
  111. * @example <u-calendar :defaultDate="defaultDateMultiple" :show="show" mode="multiple" @confirm="confirm">
  112. </u-calendar>
  113. * */
  114. export default {
  115. name: 'u-calendar',
  116. mixins: [mpMixin, mixin, props],
  117. components: {
  118. uHeader,
  119. uMonth
  120. },
  121. data() {
  122. return {
  123. // 需要显示的月份的数组
  124. months: [],
  125. // 在月份滚动区域中,当前视图中月份的index索引
  126. monthIndex: 0,
  127. // 月份滚动区域的高度
  128. listHeight: 0,
  129. // month组件中选择的日期数组
  130. selected: [],
  131. scrollIntoView: '',
  132. scrollIntoViewScroll: '',
  133. scrollTop:0,
  134. // 过滤处理方法
  135. innerFormatter: (value) => value
  136. }
  137. },
  138. watch: {
  139. scrollIntoView: {
  140. immediate: true,
  141. handler(n) {
  142. // console.log('scrollIntoView', n)
  143. }
  144. },
  145. selectedChange: {
  146. immediate: true,
  147. handler(n) {
  148. this.setMonth()
  149. }
  150. },
  151. // 打开弹窗时,设置月份数据
  152. show: {
  153. immediate: true,
  154. handler(n) {
  155. if (n) {
  156. this.setMonth()
  157. } else {
  158. // 关闭时重置scrollIntoView,否则会出现二次打开日历,当前月份数据显示不正确。
  159. // scrollIntoView需要有一个值变动过程,才会产生作用。
  160. this.scrollIntoView = ''
  161. }
  162. }
  163. }
  164. },
  165. computed: {
  166. // 由于maxDate和minDate可以为字符串(2021-10-10),或者数值(时间戳),但是dayjs如果接受字符串形式的时间戳会有问题,这里进行处理
  167. innerMaxDate() {
  168. return test.number(this.maxDate)
  169. ? Number(this.maxDate)
  170. : this.maxDate
  171. },
  172. innerMinDate() {
  173. return test.number(this.minDate)
  174. ? Number(this.minDate)
  175. : this.minDate
  176. },
  177. // 多个条件的变化,会引起选中日期的变化,这里统一管理监听
  178. selectedChange() {
  179. return [this.innerMinDate, this.innerMaxDate, this.defaultDate]
  180. },
  181. subtitle() {
  182. // 初始化时,this.months为空数组,所以需要特别判断处理
  183. if (this.months.length) {
  184. return `${this.months[this.monthIndex].year}${
  185. this.months[this.monthIndex].month
  186. }`
  187. } else {
  188. return ''
  189. }
  190. },
  191. buttonDisabled() {
  192. // 如果为range类型,且选择的日期个数不足1个时,让底部的按钮出于disabled状态
  193. if (this.mode === 'range') {
  194. if (this.selected.length <= 1) {
  195. return true
  196. } else {
  197. return false
  198. }
  199. } else {
  200. return false
  201. }
  202. }
  203. },
  204. mounted() {
  205. this.start = Date.now()
  206. this.init()
  207. },
  208. emits: ["confirm", "close"],
  209. methods: {
  210. addUnit,
  211. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  212. setFormatter(e) {
  213. this.innerFormatter = e
  214. },
  215. // month组件内部选择日期后,通过事件通知给父组件
  216. monthSelected(e,scene ='init') {
  217. this.selected = e
  218. if (!this.showConfirm) {
  219. // 在不需要确认按钮的情况下,如果为单选,或者范围多选且已选长度大于2,则直接进行返还
  220. if (
  221. this.mode === 'multiple' ||
  222. this.mode === 'single' ||
  223. (this.mode === 'range' && this.selected.length >= 2)
  224. ) {
  225. if( scene === 'init'){
  226. return
  227. }
  228. if( scene === 'tap') {
  229. this.$emit('confirm', this.selected)
  230. }
  231. }
  232. }
  233. },
  234. init() {
  235. // 校验maxDate,不能小于minDate。
  236. if (
  237. this.innerMaxDate &&
  238. this.innerMinDate &&
  239. new Date(this.innerMaxDate).getTime() < new Date(this.innerMinDate).getTime()
  240. ) {
  241. return error('maxDate不能小于minDate时间')
  242. }
  243. // 滚动区域的高度
  244. this.listHeight = this.rowHeight * 5 + 30
  245. this.setMonth()
  246. },
  247. close() {
  248. this.$emit('close')
  249. },
  250. // 点击确定按钮
  251. confirm() {
  252. if (!this.buttonDisabled) {
  253. this.$emit('confirm', this.selected)
  254. }
  255. },
  256. // 获得两个日期之间的月份数
  257. getMonths(minDate, maxDate) {
  258. const minYear = dayjs(minDate).year()
  259. const minMonth = dayjs(minDate).month() + 1
  260. const maxYear = dayjs(maxDate).year()
  261. const maxMonth = dayjs(maxDate).month() + 1
  262. return (maxYear - minYear) * 12 + (maxMonth - minMonth) + 1
  263. },
  264. // 设置月份数据
  265. setMonth() {
  266. // 最小日期的毫秒数
  267. const minDate = this.innerMinDate || dayjs().valueOf()
  268. // 如果没有指定最大日期,则往后推3个月
  269. const maxDate =
  270. this.innerMaxDate ||
  271. dayjs(minDate)
  272. .add(this.monthNum - 1, 'month')
  273. .valueOf()
  274. // 最大最小月份之间的共有多少个月份,
  275. const months = range(
  276. 1,
  277. this.monthNum,
  278. this.getMonths(minDate, maxDate)
  279. )
  280. // 先清空数组
  281. this.months = []
  282. for (let i = 0; i < months; i++) {
  283. this.months.push({
  284. date: new Array(
  285. dayjs(minDate).add(i, 'month').daysInMonth()
  286. )
  287. .fill(1)
  288. .map((item, index) => {
  289. // 日期,取值1-31
  290. let day = index + 1
  291. // 星期,0-6,0为周日
  292. const week = dayjs(minDate)
  293. .add(i, 'month')
  294. .date(day)
  295. .day()
  296. const date = dayjs(minDate)
  297. .add(i, 'month')
  298. .date(day)
  299. .format('YYYY-MM-DD')
  300. let bottomInfo = ''
  301. if (this.showLunar) {
  302. // 将日期转为农历格式
  303. const lunar = Calendar.solar2lunar(
  304. dayjs(date).year(),
  305. dayjs(date).month() + 1,
  306. dayjs(date).date()
  307. )
  308. bottomInfo = lunar.IDayCn
  309. }
  310. let config = {
  311. day,
  312. week,
  313. // 小于最小允许的日期,或者大于最大的日期,则设置为disabled状态
  314. disabled:
  315. dayjs(date).isBefore(
  316. dayjs(minDate).format('YYYY-MM-DD')
  317. ) ||
  318. dayjs(date).isAfter(
  319. dayjs(maxDate).format('YYYY-MM-DD')
  320. ),
  321. // 返回一个日期对象,供外部的formatter获取当前日期的年月日等信息,进行加工处理
  322. date: new Date(date),
  323. bottomInfo,
  324. dot: false,
  325. month:
  326. dayjs(minDate).add(i, 'month').month() + 1
  327. }
  328. const formatter =
  329. this.formatter || this.innerFormatter
  330. return formatter(config)
  331. }),
  332. // 当前所属的月份
  333. month: dayjs(minDate).add(i, 'month').month() + 1,
  334. // 当前年份
  335. year: dayjs(minDate).add(i, 'month').year()
  336. })
  337. }
  338. },
  339. // 滚动到默认设置的月份
  340. scrollIntoDefaultMonth(selected) {
  341. // 查询默认日期在可选列表的下标
  342. const _index = this.months.findIndex(({
  343. year,
  344. month
  345. }) => {
  346. month = padZero(month)
  347. return `${year}-${month}` === selected
  348. })
  349. if (_index !== -1) {
  350. // #ifndef MP-WEIXIN
  351. this.$nextTick(() => {
  352. this.scrollIntoView = `month-${_index}`
  353. this.scrollIntoViewScroll = this.scrollIntoView
  354. })
  355. // #endif
  356. // #ifdef MP-WEIXIN
  357. this.scrollTop = this.months[_index].top || 0;
  358. // #endif
  359. }
  360. },
  361. // scroll-view滚动监听
  362. onScroll(event) {
  363. // 不允许小于0的滚动值,如果scroll-view到顶了,继续下拉,会出现负数值
  364. const scrollTop = Math.max(0, event.detail.scrollTop)
  365. // 将当前滚动条数值,除以滚动区域的高度,可以得出当前滚动到了哪一个月份的索引
  366. for (let i = 0; i < this.months.length; i++) {
  367. if (scrollTop >= (this.months[i].top || this.listHeight)) {
  368. this.monthIndex = i
  369. this.scrollIntoViewScroll = `month-${i}`
  370. }
  371. }
  372. },
  373. // 更新月份的top值
  374. updateMonthTop(topArr = []) {
  375. // 设置对应月份的top值,用于onScroll方法更新月份
  376. topArr.map((item, index) => {
  377. this.months[index].top = item
  378. })
  379. // 获取默认日期的下标
  380. if (!this.defaultDate) {
  381. // 如果没有设置默认日期,则将当天日期设置为默认选中的日期
  382. const selected = dayjs().format("YYYY-MM")
  383. this.scrollIntoDefaultMonth(selected)
  384. return
  385. }
  386. let selected = dayjs().format("YYYY-MM");
  387. // 单选模式,可以是字符串或数组,Date对象等
  388. if (!test.array(this.defaultDate)) {
  389. selected = dayjs(this.defaultDate).format("YYYY-MM")
  390. } else {
  391. selected = dayjs(this.defaultDate[0]).format("YYYY-MM");
  392. }
  393. this.scrollIntoDefaultMonth(selected)
  394. }
  395. }
  396. }
  397. </script>
  398. <style lang="scss" scoped>
  399. @import '../../libs/css/components.scss';
  400. .u-calendar {
  401. &__confirm {
  402. padding: 7px 18px;
  403. }
  404. }
  405. </style>