u-calendar.vue 14 KB

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