uv-datetime-picker.vue 13 KB

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