u-calendar.vue 14 KB

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