u-datetime-picker.vue 17 KB

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