u-datetime-picker.vue 17 KB

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