猫妈狗爸伴宠师小程序前端代码
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.

497 lines
17 KiB

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