u-datetime-picker.vue 18 KB

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