u-calendar.vue 12 KB

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