month.vue 18 KB

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