month.vue 19 KB

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