You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

455 lines
16 KiB

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