u-calendar.vue 12 KB

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