u-datetime-picker.vue 16 KB

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