u-datetime-picker.vue 18 KB

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