month.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <template>
  2. <view class="u-calendar-month-wrapper" ref="u-calendar-month-wrapper">
  3. <view v-for="(item, index) in months" :key="index" :class="[`u-calendar-month-${index}`]"
  4. :ref="`u-calendar-month-${index}`" :id="`month-${index}`">
  5. <text v-if="index !== 0" class="u-calendar-month__title">{{ item.year }}年{{ item.month }}月</text>
  6. <view class="u-calendar-month__days">
  7. <view v-if="showMark" class="u-calendar-month__days__month-mark-wrapper">
  8. <text class="u-calendar-month__days__month-mark-wrapper__text">{{ item.month }}</text>
  9. </view>
  10. <view class="u-calendar-month__days__day" v-for="(item1, index1) in item.date" :key="index1"
  11. :style="[dayStyle(index, index1, item1)]" @tap="clickHandler(index, index1, item1)"
  12. :class="[item1.selected && 'u-calendar-month__days__day__select--selected']">
  13. <view class="u-calendar-month__days__day__select" :style="[daySelectStyle(index, index1, item1)]">
  14. <text class="u-calendar-month__days__day__select__info"
  15. :class="[item1.disabled && 'u-calendar-month__days__day__select__info--disabled']"
  16. :style="[textStyle(item1)]">{{ item1.day }}
  17. </text>
  18. <text v-if="getBottomInfo(index, index1, item1)"
  19. class="u-calendar-month__days__day__select__buttom-info"
  20. :class="[item1.disabled && 'u-calendar-month__days__day__select__buttom-info--disabled']"
  21. :style="[textStyle(item1)]">{{ getBottomInfo(index, index1, item1) }}
  22. </text>
  23. <text v-if="item1.dot" class="u-calendar-month__days__day__select__dot"></text>
  24. </view>
  25. </view>
  26. </view>
  27. </view>
  28. </view>
  29. </template>
  30. <script>
  31. // #ifdef APP-NVUE
  32. // 由于nvue不支持百分比单位,需要查询宽度来计算每个日期的宽度
  33. const dom = uni.requireNativePlugin('dom')
  34. // #endif
  35. import dayjs from '../../libs/util/dayjs.js';
  36. export default {
  37. name: 'u-calendar-month',
  38. mixins: [uni.$u.mpMixin, uni.$u.mixin],
  39. props: {
  40. // 是否显示月份背景色
  41. showMark: {
  42. type: Boolean,
  43. default: true
  44. },
  45. // 主题色,对底部按钮和选中日期有效
  46. color: {
  47. type: String,
  48. default: '#3c9cff'
  49. },
  50. // 月份数据
  51. months: {
  52. type: Array,
  53. default: () => []
  54. },
  55. // 日期选择类型
  56. mode: {
  57. type: String,
  58. default: 'single'
  59. },
  60. // 日期行高
  61. rowHeight: {
  62. type: [String, Number],
  63. default: 58
  64. },
  65. // mode=multiple时,最多可选多少个日期
  66. maxCount: {
  67. type: [String, Number],
  68. default: Infinity
  69. },
  70. // mode=range时,第一个日期底部的提示文字
  71. startText: {
  72. type: String,
  73. default: '开始'
  74. },
  75. // mode=range时,最后一个日期底部的提示文字
  76. endText: {
  77. type: String,
  78. default: '结束'
  79. },
  80. // 默认选中的日期,mode为multiple或range是必须为数组格式
  81. defaultDate: {
  82. type: [Array, String, Date],
  83. default: null
  84. },
  85. // 最小的可选日期
  86. minDate: {
  87. type: [String, Number],
  88. default: 0
  89. },
  90. // 最大可选日期
  91. maxDate: {
  92. type: [String, Number],
  93. default: 0
  94. },
  95. // 如果没有设置maxDate,则往后推多少个月
  96. maxMonth: {
  97. type: [String, Number],
  98. default: 2
  99. },
  100. // 是否为只读状态,只读状态下禁止选择日期
  101. readonly: {
  102. type: Boolean,
  103. default: uni.$u.props.calendar.readonly
  104. },
  105. // 日期区间最多可选天数,默认无限制,mode = range时有效
  106. maxRange: {
  107. type: [Number, String],
  108. default: Infinity
  109. },
  110. // 范围选择超过最多可选天数时的提示文案,mode = range时有效
  111. rangePrompt: {
  112. type: String,
  113. default: ''
  114. },
  115. // 范围选择超过最多可选天数时,是否展示提示文案,mode = range时有效
  116. showRangePrompt: {
  117. type: Boolean,
  118. default: true
  119. },
  120. // 是否允许日期范围的起止时间为同一天,mode = range时有效
  121. allowSameDay: {
  122. type: Boolean,
  123. default: false
  124. }
  125. },
  126. data() {
  127. return {
  128. // 每个日期的宽度
  129. width: 0,
  130. // 当前选中的日期item
  131. item: {},
  132. selected: []
  133. }
  134. },
  135. watch: {
  136. selectedChange: {
  137. immediate: true,
  138. handler(n) {
  139. this.setDefaultDate()
  140. }
  141. }
  142. },
  143. computed: {
  144. // 多个条件的变化,会引起选中日期的变化,这里统一管理监听
  145. selectedChange() {
  146. return [this.minDate, this.maxDate, this.defaultDate]
  147. },
  148. dayStyle(index1, index2, item) {
  149. return (index1, index2, item) => {
  150. const style = {}
  151. let week = item.week
  152. // 不进行四舍五入的形式保留2位小数
  153. const dayWidth = Number(parseFloat(this.width / 7).toFixed(3).slice(0, -1))
  154. // 得出每个日期的宽度
  155. // #ifdef APP-NVUE
  156. style.width = uni.$u.addUnit(dayWidth)
  157. // #endif
  158. style.height = uni.$u.addUnit(this.rowHeight)
  159. if (index2 === 0) {
  160. // 获取当前为星期几,如果为0,则为星期天,减一为每月第一天时,需要向左偏移的item个数
  161. week = (week === 0 ? 7 : week) - 1
  162. style.marginLeft = uni.$u.addUnit(week * dayWidth)
  163. }
  164. if (this.mode === 'range') {
  165. // 之所以需要这么写,是因为DCloud公司的iOS客户端的开发者能力有限导致的bug
  166. style.paddingLeft = 0
  167. style.paddingRight = 0
  168. style.paddingBottom = 0
  169. style.paddingTop = 0
  170. }
  171. return style
  172. }
  173. },
  174. daySelectStyle() {
  175. return (index1, index2, item) => {
  176. let date = dayjs(item.date).format("YYYY-MM-DD"),
  177. style = {}
  178. // 判断date是否在selected数组中,因为月份可能会需要补0,所以使用dateSame判断,而不用数组的includes判断
  179. if (this.selected.some(item => this.dateSame(item, date))) {
  180. style.backgroundColor = this.color
  181. }
  182. if (this.mode === 'single') {
  183. if (date === this.selected[0]) {
  184. // 因为需要对nvue的兼容,只能这么写,无法缩写,也无法通过类名控制等等
  185. style.borderTopLeftRadius = '3px'
  186. style.borderBottomLeftRadius = '3px'
  187. style.borderTopRightRadius = '3px'
  188. style.borderBottomRightRadius = '3px'
  189. }
  190. } else if (this.mode === 'range') {
  191. if (this.selected.length >= 2) {
  192. const len = this.selected.length - 1
  193. // 第一个日期设置左上角和左下角的圆角
  194. if (this.dateSame(date, this.selected[0])) {
  195. style.borderTopLeftRadius = '3px'
  196. style.borderBottomLeftRadius = '3px'
  197. }
  198. // 最后一个日期设置右上角和右下角的圆角
  199. if (this.dateSame(date, this.selected[len])) {
  200. style.borderTopRightRadius = '3px'
  201. style.borderBottomRightRadius = '3px'
  202. }
  203. // 处于第一和最后一个之间的日期,背景色设置为浅色,通过将对应颜色进行等分,再取其尾部的颜色值
  204. if (dayjs(date).isAfter(dayjs(this.selected[0])) && dayjs(date).isBefore(dayjs(this
  205. .selected[len]))) {
  206. style.backgroundColor = uni.$u.colorGradient(this.color, '#ffffff', 100)[90]
  207. // 增加一个透明度,让范围区间的背景色也能看到底部的mark水印字符
  208. style.opacity = 0.7
  209. }
  210. } else if (this.selected.length === 1) {
  211. // 之所以需要这么写,是因为DCloud公司的iOS客户端的开发者能力有限导致的bug
  212. // 进行还原操作,否则在nvue的iOS,uni-app有bug,会导致诡异的表现
  213. style.borderTopLeftRadius = '3px'
  214. style.borderBottomLeftRadius = '3px'
  215. }
  216. } else {
  217. if (this.selected.some(item => this.dateSame(item, date))) {
  218. style.borderTopLeftRadius = '3px'
  219. style.borderBottomLeftRadius = '3px'
  220. style.borderTopRightRadius = '3px'
  221. style.borderBottomRightRadius = '3px'
  222. }
  223. }
  224. return style
  225. }
  226. },
  227. // 某个日期是否被选中
  228. textStyle() {
  229. return (item) => {
  230. const date = dayjs(item.date).format("YYYY-MM-DD"),
  231. style = {}
  232. // 选中的日期,提示文字设置白色
  233. if (this.selected.some(item => this.dateSame(item, date))) {
  234. style.color = '#ffffff'
  235. }
  236. if (this.mode === 'range') {
  237. const len = this.selected.length - 1
  238. // 如果是范围选择模式,第一个和最后一个之间的日期,文字颜色设置为高亮的主题色
  239. if (dayjs(date).isAfter(dayjs(this.selected[0])) && dayjs(date).isBefore(dayjs(this
  240. .selected[len]))) {
  241. style.color = this.color
  242. }
  243. }
  244. return style
  245. }
  246. },
  247. // 获取底部的提示文字
  248. getBottomInfo() {
  249. return (index1, index2, item) => {
  250. const date = dayjs(item.date).format("YYYY-MM-DD")
  251. const bottomInfo = item.bottomInfo
  252. // 当为日期范围模式时,且选择的日期个数大于0时
  253. if (this.mode === 'range' && this.selected.length > 0) {
  254. if (this.selected.length === 1) {
  255. // 选择了一个日期时,如果当前日期为数组中的第一个日期,则显示底部文字为“开始”
  256. if (this.dateSame(date, this.selected[0])) return this.startText
  257. else return bottomInfo
  258. } else {
  259. const len = this.selected.length - 1
  260. // 如果数组中的日期大于2个时,第一个和最后一个显示为开始和结束日期
  261. if (this.dateSame(date, this.selected[0]) && this.dateSame(date, this.selected[1]) &&
  262. len === 1) {
  263. // 如果长度为2,且第一个等于第二个日期,则提示语放在同一个item中
  264. return `${this.startText}/${this.endText}`
  265. } else if (this.dateSame(date, this.selected[0])) {
  266. return this.startText
  267. } else if (this.dateSame(date, this.selected[len])) {
  268. return this.endText
  269. } else {
  270. return bottomInfo
  271. }
  272. }
  273. } else {
  274. return bottomInfo
  275. }
  276. }
  277. }
  278. },
  279. mounted() {
  280. this.init()
  281. },
  282. methods: {
  283. init() {
  284. // 初始化默认选中
  285. this.$emit('monthSelected', this.selected)
  286. this.$nextTick(() => {
  287. // 这里需要另一个延时,因为获取宽度后,会进行月份数据渲染,只有渲染完成之后,才有真正的高度
  288. // 因为nvue下,$nextTick并不是100%可靠的
  289. uni.$u.sleep(10).then(() => {
  290. this.getWrapperWidth()
  291. this.getMonthRect()
  292. })
  293. })
  294. },
  295. // 判断两个日期是否相等
  296. dateSame(date1, date2) {
  297. return dayjs(date1).isSame(dayjs(date2))
  298. },
  299. // 获取月份数据区域的宽度,因为nvue不支持百分比,所以无法通过css设置每个日期item的宽度
  300. getWrapperWidth() {
  301. // #ifdef APP-NVUE
  302. dom.getComponentRect(this.$refs['u-calendar-month-wrapper'], res => {
  303. this.width = res.size.width
  304. })
  305. // #endif
  306. // #ifndef APP-NVUE
  307. this.$uGetRect('.u-calendar-month-wrapper').then(size => {
  308. this.width = size.width
  309. })
  310. // #endif
  311. },
  312. getMonthRect() {
  313. // 获取每个月份数据的尺寸,用于父组件在scroll-view滚动事件中,监听当前滚动到了第几个月份
  314. const promiseAllArr = this.months.map((item, index) => this.getMonthRectByPromise(
  315. `u-calendar-month-${index}`))
  316. // 一次性返回
  317. Promise.all(promiseAllArr).then(
  318. sizes => {
  319. let height = 1
  320. const topArr = []
  321. for (let i = 0; i < this.months.length; i++) {
  322. // 添加到months数组中,供scroll-view滚动事件中,判断当前滚动到哪个月份
  323. topArr[i] = height
  324. height += sizes[i].height
  325. }
  326. // 由于微信下,无法通过this.months[i].top的形式(引用类型)去修改父组件的month的top值,所以使用事件形式对外发出
  327. this.$emit('updateMonthTop', topArr)
  328. })
  329. },
  330. // 获取每个月份区域的尺寸
  331. getMonthRectByPromise(el) {
  332. // #ifndef APP-NVUE
  333. // $uGetRect为uView自带的节点查询简化方法,详见文档介绍:https://www.uviewui.com/js/getRect.html
  334. // 组件内部一般用this.$uGetRect,对外的为uni.$u.getRect,二者功能一致,名称不同
  335. return new Promise(resolve => {
  336. this.$uGetRect(`.${el}`).then(size => {
  337. resolve(size)
  338. })
  339. })
  340. // #endif
  341. // #ifdef APP-NVUE
  342. // nvue下,使用dom模块查询元素高度
  343. // 返回一个promise,让调用此方法的主体能使用then回调
  344. return new Promise(resolve => {
  345. dom.getComponentRect(this.$refs[el][0], res => {
  346. resolve(res.size)
  347. })
  348. })
  349. // #endif
  350. },
  351. // 点击某一个日期
  352. clickHandler(index1, index2, item) {
  353. if (this.readonly) {
  354. return;
  355. }
  356. this.item = item
  357. const date = dayjs(item.date).format("YYYY-MM-DD")
  358. if (item.disabled) return
  359. // 对上一次选择的日期数组进行深度克隆
  360. let selected = uni.$u.deepClone(this.selected)
  361. if (this.mode === 'single') {
  362. // 单选情况下,让数组中的元素为当前点击的日期
  363. selected = [date]
  364. } else if (this.mode === 'multiple') {
  365. if (selected.some(item => this.dateSame(item, date))) {
  366. // 如果点击的日期已在数组中,则进行移除操作,也就是达到反选的效果
  367. const itemIndex = selected.findIndex(item => item === date)
  368. selected.splice(itemIndex, 1)
  369. } else {
  370. // 如果点击的日期不在数组中,且已有的长度小于总可选长度时,则添加到数组中去
  371. if (selected.length < this.maxCount) selected.push(date)
  372. }
  373. } else {
  374. // 选择区间形式
  375. if (selected.length === 0 || selected.length >= 2) {
  376. // 如果原来就为0或者大于2的长度,则当前点击的日期,就是开始日期
  377. selected = [date]
  378. } else if (selected.length === 1) {
  379. // 如果已经选择了开始日期
  380. const existsDate = selected[0]
  381. // 如果当前选择的日期小于上一次选择的日期,则当前的日期定为开始日期
  382. if (dayjs(date).isBefore(existsDate)) {
  383. selected = [date]
  384. } else if (dayjs(date).isAfter(existsDate)) {
  385. // 当前日期减去最大可选的日期天数,如果大于起始时间,则进行提示
  386. if (dayjs(dayjs(date).subtract(this.maxRange, 'day')).isAfter(dayjs(selected[0])) && this.showRangePrompt) {
  387. if (this.rangePrompt) {
  388. uni.$u.toast(this.rangePrompt)
  389. } else {
  390. uni.$u.toast(`选择天数不能超过 ${this.maxRange} 天`)
  391. }
  392. return
  393. }
  394. // 如果当前日期大于已有日期,将当前的添加到数组尾部
  395. selected.push(date)
  396. const startDate = selected[0]
  397. const endDate = selected[1]
  398. const arr = []
  399. let i = 0
  400. do {
  401. // 将开始和结束日期之间的日期添加到数组中
  402. arr.push(dayjs(startDate).add(i, 'day').format("YYYY-MM-DD"))
  403. i++
  404. // 累加的日期小于结束日期时,继续下一次的循环
  405. } while (dayjs(startDate).add(i, 'day').isBefore(dayjs(endDate)))
  406. // 为了一次性修改数组,避免computed中多次触发,这里才用arr变量一次性赋值的方式,同时将最后一个日期添加近来
  407. arr.push(endDate)
  408. selected = arr
  409. } else {
  410. // 选择区间时,只有一个日期的情况下,且不允许选择起止为同一天的话,不允许选择自己
  411. if (selected[0] === date && !this.allowSameDay) return
  412. selected.push(date)
  413. }
  414. }
  415. }
  416. this.setSelected(selected)
  417. },
  418. // 设置默认日期
  419. setDefaultDate() {
  420. if (!this.defaultDate) {
  421. // 如果没有设置默认日期,则将当天日期设置为默认选中的日期
  422. const selected = [dayjs().format("YYYY-MM-DD")]
  423. return this.setSelected(selected, false)
  424. }
  425. let defaultDate = []
  426. const minDate = this.minDate || dayjs().format("YYYY-MM-DD")
  427. const maxDate = this.maxDate || dayjs(minDate).add(this.maxMonth - 1, 'month').format("YYYY-MM-DD")
  428. if (this.mode === 'single') {
  429. // 单选模式,可以是字符串或数组,Date对象等
  430. if (!uni.$u.test.array(this.defaultDate)) {
  431. defaultDate = [dayjs(this.defaultDate).format("YYYY-MM-DD")]
  432. } else {
  433. defaultDate = [this.defaultDate[0]]
  434. }
  435. } else {
  436. // 如果为非数组,则不执行
  437. if (!uni.$u.test.array(this.defaultDate)) return
  438. defaultDate = this.defaultDate
  439. }
  440. // 过滤用户传递的默认数组,取出只在可允许最大值与最小值之间的元素
  441. defaultDate = defaultDate.filter(item => {
  442. return dayjs(item).isAfter(dayjs(minDate).subtract(1, 'day')) && dayjs(item).isBefore(dayjs(
  443. maxDate).add(1, 'day'))
  444. })
  445. this.setSelected(defaultDate, false)
  446. },
  447. setSelected(selected, event = true) {
  448. this.selected = selected
  449. event && this.$emit('monthSelected', this.selected)
  450. }
  451. }
  452. }
  453. </script>
  454. <style lang="scss" scoped>
  455. @import "../../libs/css/components.scss";
  456. .u-calendar-month-wrapper {
  457. margin-top: 4px;
  458. }
  459. .u-calendar-month {
  460. &__title {
  461. font-size: 14px;
  462. line-height: 42px;
  463. height: 42px;
  464. color: $u-main-color;
  465. text-align: center;
  466. font-weight: bold;
  467. }
  468. &__days {
  469. position: relative;
  470. @include flex;
  471. flex-wrap: wrap;
  472. &__month-mark-wrapper {
  473. position: absolute;
  474. top: 0;
  475. bottom: 0;
  476. left: 0;
  477. right: 0;
  478. @include flex;
  479. justify-content: center;
  480. align-items: center;
  481. &__text {
  482. font-size: 155px;
  483. color: rgba(231, 232, 234, 0.83);
  484. }
  485. }
  486. &__day {
  487. @include flex;
  488. padding: 2px;
  489. /* #ifndef APP-NVUE */
  490. // vue下使用css进行宽度计算,因为某些安卓机会无法进行js获取父元素宽度进行计算得出,会有偏移
  491. width: calc(100% / 7);
  492. box-sizing: border-box;
  493. /* #endif */
  494. &__select {
  495. flex: 1;
  496. @include flex;
  497. align-items: center;
  498. justify-content: center;
  499. position: relative;
  500. &__dot {
  501. width: 7px;
  502. height: 7px;
  503. border-radius: 100px;
  504. background-color: $u-error;
  505. position: absolute;
  506. top: 12px;
  507. right: 7px;
  508. }
  509. &__buttom-info {
  510. color: $u-content-color;
  511. text-align: center;
  512. position: absolute;
  513. bottom: 5px;
  514. font-size: 10px;
  515. text-align: center;
  516. left: 0;
  517. right: 0;
  518. &--selected {
  519. color: #ffffff;
  520. }
  521. &--disabled {
  522. color: #cacbcd;
  523. }
  524. }
  525. &__info {
  526. text-align: center;
  527. font-size: 16px;
  528. &--selected {
  529. color: #ffffff;
  530. }
  531. &--disabled {
  532. color: #cacbcd;
  533. }
  534. }
  535. &--selected {
  536. background-color: $u-primary;
  537. @include flex;
  538. justify-content: center;
  539. align-items: center;
  540. flex: 1;
  541. border-radius: 3px;
  542. }
  543. &--range-selected {
  544. opacity: 0.3;
  545. border-radius: 0;
  546. }
  547. &--range-start-selected {
  548. border-top-right-radius: 0;
  549. border-bottom-right-radius: 0;
  550. }
  551. &--range-end-selected {
  552. border-top-left-radius: 0;
  553. border-bottom-left-radius: 0;
  554. }
  555. }
  556. }
  557. }
  558. }
  559. </style>