u-datetime-picker.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <template>
  2. <view class="u-datetime-picker">
  3. <view v-if="hasInput" class="u-datetime-picker__has-input"
  4. @click="onShowByClickInput"
  5. >
  6. <slot name="trigger" :value="inputValue">
  7. <up-input
  8. :readonly="!!showByClickInput"
  9. v-model="inputValue"
  10. v-bind="inputPropsInner"
  11. ></up-input>
  12. <div class="input-cover">
  13. </div>
  14. </slot>
  15. </view>
  16. <u-picker
  17. ref="picker"
  18. :show="show || (hasInput && showByClickInput)"
  19. :popupMode="popupMode"
  20. :closeOnClickOverlay="closeOnClickOverlay"
  21. :columns="columns"
  22. :title="title"
  23. :itemHeight="itemHeight"
  24. :showToolbar="showToolbar"
  25. :visibleItemCount="visibleItemCount"
  26. :defaultIndex="innerDefaultIndex"
  27. :cancelText="cancelText"
  28. :confirmText="confirmText"
  29. :cancelColor="cancelColor"
  30. :confirmColor="confirmColor"
  31. :toolbarRightSlot="toolbarRightSlot"
  32. @close="close"
  33. @cancel="cancel"
  34. @confirm="confirm"
  35. @change="change"
  36. >
  37. <template #toolbar-right>
  38. <slot name="toolbar-right">
  39. </slot>
  40. </template>
  41. <template #toolbar-bottom>
  42. <slot name="toolbar-bottom">
  43. </slot>
  44. </template>
  45. </u-picker>
  46. </view>
  47. </template>
  48. <script>
  49. function times(n, iteratee) {
  50. let index = -1
  51. const result = Array(n < 0 ? 0 : n)
  52. while (++index < n) {
  53. result[index] = iteratee(index)
  54. }
  55. return result
  56. }
  57. import { props } from './props';
  58. import { mpMixin } from '../../libs/mixin/mpMixin';
  59. import { mixin } from '../../libs/mixin/mixin';
  60. import dayjs from 'dayjs/esm/index';
  61. import { range, error, padZero } from '../../libs/function/index';
  62. import test from '../../libs/function/test';
  63. /**
  64. * DatetimePicker 时间日期选择器
  65. * @description 此选择器用于时间日期
  66. * @tutorial https://ijry.github.io/uview-plus/components/datetimePicker.html
  67. * @property {Boolean} show 用于控制选择器的弹出与收起 ( 默认 false )
  68. * @property {Boolean} showToolbar 是否显示顶部的操作栏 ( 默认 true )
  69. * @property {String | Number} modelValue 绑定值
  70. * @property {String} title 顶部标题
  71. * @property {String} mode 展示格式 mode=date为日期选择,mode=time为时间选择,mode=year-month为年月选择,mode=datetime为日期时间选择 ( 默认 ‘datetime )
  72. * @property {Number} maxDate 可选的最大时间 默认值为后10年
  73. * @property {Number} minDate 可选的最小时间 默认值为前10年
  74. * @property {Number} minHour 可选的最小小时,仅mode=time有效 ( 默认 0 )
  75. * @property {Number} maxHour 可选的最大小时,仅mode=time有效 ( 默认 23 )
  76. * @property {Number} minMinute 可选的最小分钟,仅mode=time有效 ( 默认 0 )
  77. * @property {Number} maxMinute 可选的最大分钟,仅mode=time有效 ( 默认 59 )
  78. * @property {Function} filter 选项过滤函数
  79. * @property {Function} formatter 选项格式化函数
  80. * @property {Boolean} loading 是否显示加载中状态 ( 默认 false )
  81. * @property {String | Number} itemHeight 各列中,单个选项的高度 ( 默认 44 )
  82. * @property {String} cancelText 取消按钮的文字 ( 默认 '取消' )
  83. * @property {String} confirmText 确认按钮的文字 ( 默认 '确认' )
  84. * @property {String} cancelColor 取消按钮的颜色 ( 默认 '#909193' )
  85. * @property {String} confirmColor 确认按钮的颜色 ( 默认 '#3c9cff' )
  86. * @property {String | Number} visibleItemCount 每列中可见选项的数量 ( 默认 5 )
  87. * @property {Boolean} closeOnClickOverlay 是否允许点击遮罩关闭选择器 ( 默认 false )
  88. * @property {Array} defaultIndex 各列的默认索引
  89. * @event {Function} close 关闭选择器时触发
  90. * @event {Function} confirm 点击确定按钮,返回当前选择的值
  91. * @event {Function} change 当选择值变化时触发
  92. * @event {Function} cancel 点击取消按钮
  93. * @example <u-datetime-picker :show="show" :value="value1" mode="datetime" ></u-datetime-picker>
  94. */
  95. export default {
  96. name: 'up-datetime-picker',
  97. mixins: [mpMixin, mixin, props],
  98. data() {
  99. return {
  100. // 原来的日期选择器不方便,这里增加一个hasInput选项支持类似element的自带输入框的功能。
  101. inputValue: '', // 表单显示值
  102. showByClickInput: false, // 是否在hasInput模式下显示日期选择弹唱
  103. columns: [],
  104. innerDefaultIndex: [],
  105. innerFormatter: (type, value) => value
  106. }
  107. },
  108. watch: {
  109. show(newValue, oldValue) {
  110. if (newValue) {
  111. // #ifdef VUE3
  112. this.innerValue = this.correctValue(this.modelValue)
  113. // #endif
  114. // #ifdef VUE2
  115. this.innerValue = this.correctValue(this.value)
  116. // #endif
  117. this.updateColumnValue(this.innerValue)
  118. }
  119. },
  120. // #ifdef VUE3
  121. modelValue(newValue) {
  122. this.init()
  123. // this.getInputValue(newValue)
  124. },
  125. // #endif
  126. // #ifdef VUE2
  127. value(newValue) {
  128. this.init()
  129. // this.getInputValue(newValue)
  130. },
  131. // #endif
  132. propsChange() {
  133. this.init()
  134. }
  135. },
  136. computed: {
  137. // 如果以下这些变量发生了变化,意味着需要重新初始化各列的值
  138. propsChange() {
  139. return [this.mode, this.maxDate, this.minDate, this.minHour, this.maxHour, this.minMinute, this.maxMinute, this.filter, this.modelValue]
  140. },
  141. // input的props
  142. inputPropsInner() {
  143. return {
  144. border: this.inputBorder,
  145. placeholder: this.placeholder,
  146. disabled: this.disabled,
  147. disabledColor: this.disabledColor,
  148. ...this.inputProps
  149. }
  150. }
  151. },
  152. mounted() {
  153. this.init()
  154. },
  155. // #ifdef VUE3
  156. emits: ['close', 'cancel', 'confirm', 'change', 'update:modelValue'],
  157. // #endif
  158. methods: {
  159. getInputValue(newValue) {
  160. if (newValue == '' || !newValue || newValue == undefined) {
  161. this.inputValue = ''
  162. return
  163. }
  164. if (this.mode == 'time') {
  165. this.inputValue = newValue
  166. } else {
  167. if (this.format) {
  168. this.inputValue = dayjs(newValue).format(this.format)
  169. } else {
  170. let format = ''
  171. switch (this.mode) {
  172. case 'date':
  173. format = 'YYYY-MM-DD'
  174. break;
  175. case 'year-month':
  176. format = 'YYYY-MM'
  177. break;
  178. case 'datetime':
  179. format = 'YYYY-MM-DD HH:mm'
  180. break;
  181. case 'time':
  182. format = 'HH:mm'
  183. break;
  184. default:
  185. break;
  186. }
  187. this.inputValue = dayjs(newValue).format(format)
  188. }
  189. }
  190. },
  191. init() {
  192. // #ifdef VUE3
  193. this.innerValue = this.correctValue(this.modelValue)
  194. // #endif
  195. // #ifdef VUE2
  196. this.innerValue = this.correctValue(this.value)
  197. // #endif
  198. this.updateColumnValue(this.innerValue)
  199. // 初始化hasInput展示
  200. this.getInputValue(this.innerValue)
  201. },
  202. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  203. setFormatter(e) {
  204. this.innerFormatter = e
  205. },
  206. // 关闭选择器
  207. close() {
  208. if (this.closeOnClickOverlay) {
  209. this.$emit('close')
  210. }
  211. },
  212. // 点击工具栏的取消按钮
  213. cancel() {
  214. if (this.hasInput) {
  215. this.showByClickInput = false
  216. }
  217. this.$emit('cancel')
  218. },
  219. // 点击工具栏的确定按钮
  220. confirm() {
  221. // #ifdef VUE3
  222. this.$emit('update:modelValue', this.innerValue)
  223. // #endif
  224. // #ifdef VUE2
  225. this.$emit('input', this.innerValue)
  226. // #endif
  227. if (this.hasInput) {
  228. this.getInputValue(this.innerValue)
  229. this.showByClickInput = false
  230. }
  231. this.$emit('confirm', {
  232. value: this.innerValue,
  233. mode: this.mode
  234. })
  235. },
  236. //用正则截取输出值,当出现多组数字时,抛出错误
  237. intercept(e,type){
  238. let judge = e.match(/\d+/g)
  239. //判断是否掺杂数字
  240. if(judge.length>1){
  241. error("请勿在过滤或格式化函数时添加数字")
  242. return 0
  243. }else if(type&&judge[0].length==4){//判断是否是年份
  244. return judge[0]
  245. }else if(judge[0].length>2){
  246. error("请勿在过滤或格式化函数时添加数字")
  247. return 0
  248. }else{
  249. return judge[0]
  250. }
  251. },
  252. // 列发生变化时触发
  253. change(e) {
  254. const { indexs, values } = e
  255. let selectValue = ''
  256. if(this.mode === 'time') {
  257. // 根据value各列索引,从各列数组中,取出当前时间的选中值
  258. selectValue = `${this.intercept(values[0][indexs[0]])}:${this.intercept(values[1][indexs[1]])}`
  259. } else {
  260. // 将选择的值转为数值,比如'03'转为数值的3,'2019'转为数值的2019
  261. const year = parseInt(this.intercept(values[0][indexs[0]],'year'))
  262. const month = parseInt(this.intercept(values[1][indexs[1]]))
  263. let date = parseInt(values[2] ? this.intercept(values[2][indexs[2]]) : 1)
  264. let hour = 0, minute = 0
  265. // 此月份的最大天数
  266. const maxDate = dayjs(`${year}-${month}`).daysInMonth()
  267. // year-month模式下,date不会出现在列中,设置为1,为了符合后边需要减1的需求
  268. if (this.mode === 'year-month') {
  269. date = 1
  270. }
  271. // 不允许超过maxDate值
  272. date = Math.min(maxDate, date)
  273. if (this.mode === 'datetime') {
  274. hour = parseInt(this.intercept(values[3][indexs[3]]))
  275. minute = parseInt(this.intercept(values[4][indexs[4]]))
  276. }
  277. // 转为时间模式
  278. selectValue = Number(new Date(year, month - 1, date, hour, minute))
  279. }
  280. // 取出准确的合法值,防止超越边界的情况
  281. selectValue = this.correctValue(selectValue)
  282. this.innerValue = selectValue
  283. this.updateColumnValue(selectValue)
  284. // 发出change时间,value为当前选中的时间戳
  285. this.$emit('change', {
  286. value: selectValue,
  287. // #ifndef MP-WEIXIN
  288. // 微信小程序不能传递this实例,会因为循环引用而报错
  289. // picker: this.$refs.picker,
  290. // #endif
  291. mode: this.mode
  292. })
  293. },
  294. // 更新各列的值,进行补0、格式化等操作
  295. updateColumnValue(value) {
  296. this.innerValue = value
  297. this.updateColumns()
  298. // 延迟执行,等待u-picker组件列数据更新完后再设置选中值索引
  299. setTimeout(() => {
  300. this.updateIndexs(value)
  301. }, 0);
  302. },
  303. // 更新索引
  304. updateIndexs(value) {
  305. let values = []
  306. const formatter = this.formatter || this.innerFormatter
  307. if (this.mode === 'time') {
  308. // 将time模式的时间用:分隔成数组
  309. const timeArr = value.split(':')
  310. // 使用formatter格式化方法进行管道处理
  311. values = [formatter('hour', timeArr[0]), formatter('minute', timeArr[1])]
  312. } else {
  313. const date = new Date(value)
  314. values = [
  315. formatter('year', `${dayjs(value).year()}`),
  316. // 月份补0
  317. formatter('month', padZero(dayjs(value).month() + 1))
  318. ]
  319. if (this.mode === 'date') {
  320. // date模式,需要添加天列
  321. values.push(formatter('day', padZero(dayjs(value).date())))
  322. }
  323. if (this.mode === 'datetime') {
  324. // 数组的push方法,可以写入多个参数
  325. values.push(formatter('day', padZero(dayjs(value).date())), formatter('hour', padZero(dayjs(value).hour())), formatter('minute', padZero(dayjs(value).minute())))
  326. }
  327. }
  328. // 根据当前各列的所有值,从各列默认值中找到默认值在各列中的索引
  329. const indexs = this.columns.map((column, index) => {
  330. // 通过取大值,可以保证不会出现找不到索引的-1情况
  331. return Math.max(0, column.findIndex(item => item === values[index]))
  332. })
  333. this.innerDefaultIndex = indexs
  334. },
  335. // 更新各列的值
  336. updateColumns() {
  337. const formatter = this.formatter || this.innerFormatter
  338. // 获取各列的值,并且map后,对各列的具体值进行补0操作
  339. const results = this.getOriginColumns().map((column) => column.values.map((value) => formatter(column.type, value)))
  340. this.columns = results
  341. },
  342. getOriginColumns() {
  343. // 生成各列的值
  344. const results = this.getRanges().map(({ type, range }) => {
  345. let values = times(range[1] - range[0] + 1, (index) => {
  346. let value = range[0] + index
  347. value = type === 'year' ? `${value}` : padZero(value)
  348. return value
  349. })
  350. // 进行过滤
  351. if (this.filter) {
  352. values = this.filter(type, values)
  353. if (!values || (values && values.length == 0)) {
  354. // uni.showToast({
  355. // title: '日期filter结果不能为空',
  356. // icon: 'error',
  357. // mask: true
  358. // })
  359. console.log('日期filter结果不能为空')
  360. }
  361. }
  362. return { type, values }
  363. })
  364. return results
  365. },
  366. // 通过最大值和最小值生成数组
  367. generateArray(start, end) {
  368. return Array.from(new Array(end + 1).keys()).slice(start)
  369. },
  370. // 得出合法的时间
  371. correctValue(value) {
  372. const isDateMode = this.mode !== 'time'
  373. // if (isDateMode && !test.date(value)) {
  374. if (isDateMode && !dayjs.unix(value).isValid()) {
  375. // 如果是日期类型,但是又没有设置合法的当前时间的话,使用最小时间为当前时间
  376. value = this.minDate
  377. } else if (!isDateMode && !value) {
  378. // 如果是时间类型,而又没有默认值的话,就用最小时间
  379. value = `${padZero(this.minHour)}:${padZero(this.minMinute)}`
  380. }
  381. // 时间类型
  382. if (!isDateMode) {
  383. if (String(value).indexOf(':') === -1) return error('时间错误,请传递如12:24的格式')
  384. let [hour, minute] = value.split(':')
  385. // 对时间补零,同时控制在最小值和最大值之间
  386. hour = padZero(range(this.minHour, this.maxHour, Number(hour)))
  387. minute = padZero(range(this.minMinute, this.maxMinute, Number(minute)))
  388. return `${ hour }:${ minute }`
  389. } else {
  390. // 如果是日期格式,控制在最小日期和最大日期之间
  391. value = dayjs(value).isBefore(dayjs(this.minDate)) ? this.minDate : value
  392. value = dayjs(value).isAfter(dayjs(this.maxDate)) ? this.maxDate : value
  393. return value
  394. }
  395. },
  396. // 获取每列的最大和最小值
  397. getRanges() {
  398. if (this.mode === 'time') {
  399. return [
  400. {
  401. type: 'hour',
  402. range: [this.minHour, this.maxHour],
  403. },
  404. {
  405. type: 'minute',
  406. range: [this.minMinute, this.maxMinute],
  407. },
  408. ];
  409. }
  410. const { maxYear, maxDate, maxMonth, maxHour, maxMinute, } = this.getBoundary('max', this.innerValue);
  411. const { minYear, minDate, minMonth, minHour, minMinute, } = this.getBoundary('min', this.innerValue);
  412. const result = [
  413. {
  414. type: 'year',
  415. range: [minYear, maxYear],
  416. },
  417. {
  418. type: 'month',
  419. range: [minMonth, maxMonth],
  420. },
  421. {
  422. type: 'day',
  423. range: [minDate, maxDate],
  424. },
  425. {
  426. type: 'hour',
  427. range: [minHour, maxHour],
  428. },
  429. {
  430. type: 'minute',
  431. range: [minMinute, maxMinute],
  432. },
  433. ];
  434. if (this.mode === 'date')
  435. result.splice(3, 2);
  436. if (this.mode === 'year-month')
  437. result.splice(2, 3);
  438. return result;
  439. },
  440. // 根据minDate、maxDate、minHour、maxHour等边界值,判断各列的开始和结束边界值
  441. getBoundary(type, innerValue) {
  442. let value = new Date(innerValue)
  443. if(isNaN(value.getTime())){
  444. value = new Date()
  445. }
  446. const boundary = new Date(this[`${type}Date`])
  447. const year = dayjs(boundary).year()
  448. let month = 1
  449. let date = 1
  450. let hour = 0
  451. let minute = 0
  452. if (type === 'max') {
  453. month = 12
  454. // 月份的天数
  455. date = dayjs(value).daysInMonth()
  456. hour = 23
  457. minute = 59
  458. }
  459. // 获取边界值,逻辑是:当年达到了边界值(最大或最小年),就检查月允许的最大和最小值,以此类推
  460. if (dayjs(value).year() === year) {
  461. month = dayjs(boundary).month() + 1
  462. if (dayjs(value).month() + 1 === month) {
  463. date = dayjs(boundary).date()
  464. if (dayjs(value).date() === date) {
  465. hour = dayjs(boundary).hour()
  466. if (dayjs(value).hour() === hour) {
  467. minute = dayjs(boundary).minute()
  468. }
  469. }
  470. }
  471. }
  472. return {
  473. [`${type}Year`]: year,
  474. [`${type}Month`]: month,
  475. [`${type}Date`]: date,
  476. [`${type}Hour`]: hour,
  477. [`${type}Minute`]: minute
  478. }
  479. },
  480. onShowByClickInput(){
  481. if(!this.disabled){
  482. this.showByClickInput = !this.showByClickInput
  483. }
  484. }
  485. }
  486. }
  487. </script>
  488. <style lang="scss" scoped>
  489. .u-datetime-picker {
  490. flex: 1;
  491. &__has-input {
  492. position: relative;
  493. display: flex;
  494. flex-direction: column;
  495. justify-content: center;
  496. /* #ifndef APP-NVUE */
  497. width: 100%;
  498. /* #endif */
  499. .input-cover {
  500. opacity: 0;
  501. position: absolute;
  502. top: 0;
  503. bottom: 0;
  504. left:0;
  505. right:0;
  506. display: flex;
  507. flex-direction: column;
  508. justify-content: center;
  509. border-radius: 4px;
  510. border: 1px solid #eee;
  511. padding: 0 10px;
  512. }
  513. }
  514. }
  515. </style>