uv-datetime-picker.vue 13 KB

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