u-datetime-picker.vue 14 KB

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