康巴易测肤/伤疤uniapp小程序类
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

362 行
13KB

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