u-datetime-picker.vue 17 KB

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