u-datetime-picker.vue 16 KB

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