u-datetime-picker.vue 16 KB

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