u-calendar.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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/esm/index'
  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. emits: ["confirm", "close"],
  195. methods: {
  196. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  197. setFormatter(e) {
  198. this.innerFormatter = e
  199. },
  200. // month组件内部选择日期后,通过事件通知给父组件
  201. monthSelected(e) {
  202. this.selected = e
  203. if (!this.showConfirm) {
  204. // 在不需要确认按钮的情况下,如果为单选,或者范围多选且已选长度大于2,则直接进行返还
  205. if (
  206. this.mode === 'multiple' ||
  207. this.mode === 'single' ||
  208. (this.mode === 'range' && this.selected.length >= 2)
  209. ) {
  210. this.$emit('confirm', this.selected)
  211. }
  212. }
  213. },
  214. init() {
  215. // 校验maxDate,不能小于当前时间
  216. if (
  217. this.innerMaxDate &&
  218. new Date(this.innerMaxDate).getTime() <= Date.now()
  219. ) {
  220. return uni.$u.error('maxDate不能小于当前时间')
  221. }
  222. // 滚动区域的高度
  223. this.listHeight = this.rowHeight * 5 + 30
  224. this.setMonth()
  225. },
  226. close() {
  227. this.$emit('close')
  228. },
  229. // 点击确定按钮
  230. confirm() {
  231. if (!this.buttonDisabled) {
  232. this.$emit('confirm', this.selected)
  233. }
  234. },
  235. // 获得两个日期之间的月份数
  236. getMonths(minDate, maxDate) {
  237. const minYear = dayjs(minDate).year()
  238. const minMonth = dayjs(minDate).month() + 1
  239. const maxYear = dayjs(maxDate).year()
  240. const maxMonth = dayjs(maxDate).month() + 1
  241. return (maxYear - minYear) * 12 + (maxMonth - minMonth) + 1
  242. },
  243. // 设置月份数据
  244. setMonth() {
  245. // 最小日期的毫秒数
  246. const minDate = this.innerMinDate || dayjs().valueOf()
  247. // 如果没有指定最大日期,则往后推3个月
  248. const maxDate =
  249. this.innerMaxDate ||
  250. dayjs(minDate)
  251. .add(this.monthNum - 1, 'month')
  252. .valueOf()
  253. // 最大最小月份之间的共有多少个月份,
  254. const months = uni.$u.range(
  255. 1,
  256. this.monthNum,
  257. this.getMonths(minDate, maxDate)
  258. )
  259. // 先清空数组
  260. this.months = []
  261. for (let i = 0; i < months; i++) {
  262. this.months.push({
  263. date: new Array(
  264. dayjs(minDate).add(i, 'month').daysInMonth()
  265. )
  266. .fill(1)
  267. .map((item, index) => {
  268. // 日期,取值1-31
  269. let day = index + 1
  270. // 星期,0-6,0为周日
  271. const week = dayjs(minDate)
  272. .add(i, 'month')
  273. .date(day)
  274. .day()
  275. const date = dayjs(minDate)
  276. .add(i, 'month')
  277. .date(day)
  278. .format('YYYY-MM-DD')
  279. let bottomInfo = ''
  280. if (this.showLunar) {
  281. // 将日期转为农历格式
  282. const lunar = Calendar.solar2lunar(
  283. dayjs(date).year(),
  284. dayjs(date).month() + 1,
  285. dayjs(date).date()
  286. )
  287. bottomInfo = lunar.IDayCn
  288. }
  289. let config = {
  290. day,
  291. week,
  292. // 小于最小允许的日期,或者大于最大的日期,则设置为disabled状态
  293. disabled:
  294. dayjs(date).isBefore(
  295. dayjs(minDate).format('YYYY-MM-DD')
  296. ) ||
  297. dayjs(date).isAfter(
  298. dayjs(maxDate).format('YYYY-MM-DD')
  299. ),
  300. // 返回一个日期对象,供外部的formatter获取当前日期的年月日等信息,进行加工处理
  301. date: new Date(date),
  302. bottomInfo,
  303. dot: false,
  304. month:
  305. dayjs(minDate).add(i, 'month').month() + 1
  306. }
  307. const formatter =
  308. this.formatter || this.innerFormatter
  309. return formatter(config)
  310. }),
  311. // 当前所属的月份
  312. month: dayjs(minDate).add(i, 'month').month() + 1,
  313. // 当前年份
  314. year: dayjs(minDate).add(i, 'month').year()
  315. })
  316. }
  317. },
  318. // 滚动到默认设置的月份
  319. scrollIntoDefaultMonth(selected) {
  320. // 查询默认日期在可选列表的下标
  321. const _index = this.months.findIndex(({
  322. year,
  323. month
  324. }) => {
  325. month = uni.$u.padZero(month)
  326. return `${year}-${month}` === selected
  327. })
  328. if (_index !== -1) {
  329. // #ifndef MP-WEIXIN
  330. this.$nextTick(() => {
  331. this.scrollIntoView = `month-${_index}`
  332. })
  333. // #endif
  334. // #ifdef MP-WEIXIN
  335. this.scrollTop = this.months[_index].top || 0;
  336. // #endif
  337. }
  338. },
  339. // scroll-view滚动监听
  340. onScroll(event) {
  341. // 不允许小于0的滚动值,如果scroll-view到顶了,继续下拉,会出现负数值
  342. const scrollTop = Math.max(0, event.detail.scrollTop)
  343. // 将当前滚动条数值,除以滚动区域的高度,可以得出当前滚动到了哪一个月份的索引
  344. for (let i = 0; i < this.months.length; i++) {
  345. if (scrollTop >= (this.months[i].top || this.listHeight)) {
  346. this.monthIndex = i
  347. }
  348. }
  349. },
  350. // 更新月份的top值
  351. updateMonthTop(topArr = []) {
  352. // 设置对应月份的top值,用于onScroll方法更新月份
  353. topArr.map((item, index) => {
  354. this.months[index].top = item
  355. })
  356. // 获取默认日期的下标
  357. if (!this.defaultDate) {
  358. // 如果没有设置默认日期,则将当天日期设置为默认选中的日期
  359. const selected = dayjs().format("YYYY-MM")
  360. this.scrollIntoDefaultMonth(selected)
  361. return
  362. }
  363. let selected = dayjs().format("YYYY-MM");
  364. // 单选模式,可以是字符串或数组,Date对象等
  365. if (!uni.$u.test.array(this.defaultDate)) {
  366. selected = dayjs(this.defaultDate).format("YYYY-MM")
  367. } else {
  368. selected = dayjs(this.defaultDate[0]).format("YYYY-MM");
  369. }
  370. this.scrollIntoDefaultMonth(selected)
  371. }
  372. }
  373. }
  374. </script>
  375. <style lang="scss" scoped>
  376. @import '../../libs/css/components.scss';
  377. .u-calendar {
  378. &__confirm {
  379. padding: 7px 18px;
  380. }
  381. }
  382. </style>