index.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. import {
  2. number as testNumber,
  3. array as testArray,
  4. empty as testEmpty
  5. } from './test'
  6. import { round } from './digit.js'
  7. import config from '../config/config';
  8. /**
  9. * @description 如果value小于min,取min;如果value大于max,取max
  10. * @param {number} min
  11. * @param {number} max
  12. * @param {number} value
  13. */
  14. export function range(min = 0, max = 0, value = 0) {
  15. return Math.max(min, Math.min(max, Number(value)))
  16. }
  17. /**
  18. * @description 用于获取用户传递值的px值 如果用户传递了"xxpx"或者"xxrpx",取出其数值部分,如果是"xxxrpx"还需要用过uni.rpx2px进行转换
  19. * @param {number|string} value 用户传递值的px值
  20. * @param {boolean} unit
  21. * @returns {number|string}
  22. */
  23. export function getPx(value, unit = false) {
  24. if (testNumber(value)) {
  25. return unit ? `${value}px` : Number(value)
  26. }
  27. // 如果带有rpx,先取出其数值部分,再转为px值
  28. if (/(rpx|upx)$/.test(value)) {
  29. return unit ? `${uni.rpx2px(parseInt(value))}px` : Number(uni.rpx2px(parseInt(value)))
  30. }
  31. return unit ? `${parseInt(value)}px` : parseInt(value)
  32. }
  33. /**
  34. * @description 进行延时,以达到可以简写代码的目的 比如: await uni.$u.sleep(20)将会阻塞20ms
  35. * @param {number} value 堵塞时间 单位ms 毫秒
  36. * @returns {Promise} 返回promise
  37. */
  38. export function sleep(value = 30) {
  39. return new Promise((resolve) => {
  40. setTimeout(() => {
  41. resolve()
  42. }, value)
  43. })
  44. }
  45. /**
  46. * @description 运行期判断平台
  47. * @returns {string} 返回所在平台(小写)
  48. * @link 运行期判断平台 https://uniapp.dcloud.io/frame?id=判断平台
  49. */
  50. export function os() {
  51. // 安全获取windowInfo,避免为null/undefined
  52. const windowInfo = uni.getWindowInfo() || {};
  53. // 提取platform,默认空字符串兜底
  54. const platform = windowInfo.platform || '';
  55. // 确保转为字符串后再调用toLowerCase()
  56. return String(platform).toLowerCase();
  57. }
  58. /**
  59. * @description 获取系统信息同步接口
  60. * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getWindowInfo
  61. */
  62. export function sys() {
  63. return uni.getWindowInfo()
  64. }
  65. /**
  66. * @description 取一个区间数
  67. * @param {Number} min 最小值
  68. * @param {Number} max 最大值
  69. */
  70. export function random(min, max) {
  71. if (min >= 0 && max > 0 && max >= min) {
  72. const gab = max - min + 1
  73. return Math.floor(Math.random() * gab + min)
  74. }
  75. return 0
  76. }
  77. /**
  78. * @param {Number} len uuid的长度
  79. * @param {Boolean} firstU 将返回的首字母置为"u"
  80. * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
  81. */
  82. export function guid(len = 32, firstU = true, radix = null) {
  83. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  84. const uuid = []
  85. radix = radix || chars.length
  86. if (len) {
  87. // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
  88. for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
  89. } else {
  90. let r
  91. // rfc4122标准要求返回的uuid中,某些位为固定的字符
  92. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
  93. uuid[14] = '4'
  94. for (let i = 0; i < 36; i++) {
  95. if (!uuid[i]) {
  96. r = 0 | Math.random() * 16
  97. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
  98. }
  99. }
  100. }
  101. // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  102. if (firstU) {
  103. uuid.shift()
  104. return `u${uuid.join('')}`
  105. }
  106. return uuid.join('')
  107. }
  108. /**
  109. * @description 获取父组件的参数,因为支付宝小程序不支持provide/inject的写法
  110. this.$parent在非H5中,可以准确获取到父组件,但是在H5中,需要多次this.$parent.$parent.xxx
  111. 这里默认值等于undefined有它的含义,因为最顶层元素(组件)的$parent就是undefined,意味着不传name
  112. 值(默认为undefined),就是查找最顶层的$parent
  113. * @param {string|undefined} name 父组件的参数名
  114. */
  115. export function $parent(name = undefined) {
  116. let parent = this.$parent
  117. // 通过while历遍,这里主要是为了H5需要多层解析的问题
  118. while (parent) {
  119. // 父组件
  120. if (parent.$options && parent.$options.name !== name) {
  121. // 如果组件的name不相等,继续上一级寻找
  122. parent = parent.$parent
  123. } else {
  124. return parent
  125. }
  126. }
  127. return false
  128. }
  129. /**
  130. * @description 样式转换
  131. * 对象转字符串,或者字符串转对象
  132. * @param {object | string} customStyle 需要转换的目标
  133. * @param {String} target 转换的目的,object-转为对象,string-转为字符串
  134. * @returns {object|string}
  135. */
  136. export function addStyle(customStyle, target = 'object') {
  137. // 字符串转字符串,对象转对象情形,直接返回
  138. if (testEmpty(customStyle) || typeof(customStyle) === 'object' && target === 'object' || target === 'string' &&
  139. typeof(customStyle) === 'string') {
  140. return customStyle
  141. }
  142. // 字符串转对象
  143. if (target === 'object') {
  144. // 去除字符串样式中的两端空格(中间的空格不能去掉,比如padding: 20px 0如果去掉了就错了),空格是无用的
  145. customStyle = trim(customStyle)
  146. // 根据";"将字符串转为数组形式
  147. const styleArray = customStyle.split(';')
  148. const style = {}
  149. // 历遍数组,拼接成对象
  150. for (let i = 0; i < styleArray.length; i++) {
  151. // 'font-size:20px;color:red;',如此最后字符串有";"的话,会导致styleArray最后一个元素为空字符串,这里需要过滤
  152. if (styleArray[i]) {
  153. const item = styleArray[i].split(':')
  154. style[trim(item[0])] = trim(item[1])
  155. }
  156. }
  157. return style
  158. }
  159. // 这里为对象转字符串形式
  160. let string = ''
  161. if (typeof customStyle === 'object') {
  162. customStyle.forEach((val, i) => {
  163. // 驼峰转为中划线的形式,否则css内联样式,无法识别驼峰样式属性名
  164. const key = i.replace(/([A-Z])/g, '-$1').toLowerCase()
  165. string += `${key}:${val};`
  166. })
  167. }
  168. // 去除两端空格
  169. return trim(string)
  170. }
  171. /**
  172. * @description 添加单位,如果有rpx,upx,%,px等单位结尾或者值为auto,直接返回,否则加上px单位结尾
  173. * @param {string|number} value 需要添加单位的值
  174. * @param {string} unit 添加的单位名 比如px
  175. */
  176. export function addUnit(value = 'auto', unit = '') {
  177. if (!unit) {
  178. unit = config.unit || 'px'
  179. }
  180. value = String(value)
  181. // 用uView内置验证规则中的number判断是否为数值
  182. return testNumber(value) ? `${value}${unit}` : value
  183. }
  184. /**
  185. * @description 深度克隆
  186. * @param {object} obj 需要深度克隆的对象
  187. * @returns {*} 克隆后的对象或者原值(不是对象)
  188. */
  189. export function deepClone(obj) {
  190. // 对常见的“非”值,直接返回原来值
  191. if ([null, undefined, NaN, false].includes(obj)) return obj
  192. if (typeof obj !== 'object' && typeof obj !== 'function') {
  193. // 原始类型直接返回
  194. return obj
  195. }
  196. const o = testArray(obj) ? [] : {}
  197. for (const i in obj) {
  198. if (obj.hasOwnProperty(i)) {
  199. o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]
  200. }
  201. }
  202. return o
  203. }
  204. /**
  205. * @description JS对象深度合并
  206. * @param {object} target 需要拷贝的对象
  207. * @param {object} source 拷贝的来源对象
  208. * @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象)
  209. */
  210. export function deepMerge(targetOrigin = {}, source = {}) {
  211. let target = deepClone(targetOrigin)
  212. if (typeof target !== 'object' || typeof source !== 'object') return false
  213. for (const prop in source) {
  214. if (!source.hasOwnProperty(prop)) continue
  215. if (prop in target) {
  216. if (source[prop] == null) {
  217. target[prop] = source[prop]
  218. }else if (typeof target[prop] !== 'object') {
  219. target[prop] = source[prop]
  220. } else if (typeof source[prop] !== 'object') {
  221. target[prop] = source[prop]
  222. } else if (target[prop].concat && source[prop].concat) {
  223. target[prop] = target[prop].concat(source[prop])
  224. } else {
  225. target[prop] = deepMerge(target[prop], source[prop])
  226. }
  227. } else {
  228. target[prop] = source[prop]
  229. }
  230. }
  231. return target
  232. }
  233. /**
  234. * @description JS对象深度合并
  235. * @param {object} target 需要拷贝的对象
  236. * @param {object} source 拷贝的来源对象
  237. * @returns {object|boolean} 深度合并后的对象或者false(入参有不是对象)
  238. */
  239. export function shallowMerge(target, source = {}) {
  240. if (typeof target !== 'object' || typeof source !== 'object') return false
  241. for (const prop in source) {
  242. if (!source.hasOwnProperty(prop)) continue
  243. if (prop in target) {
  244. if (source[prop] == null) {
  245. target[prop] = source[prop]
  246. }else if (typeof target[prop] !== 'object') {
  247. target[prop] = source[prop]
  248. } else if (typeof source[prop] !== 'object') {
  249. target[prop] = source[prop]
  250. } else if (target[prop].concat && source[prop].concat) {
  251. target[prop] = target[prop].concat(source[prop])
  252. } else {
  253. target[prop] = shallowMerge(target[prop], source[prop])
  254. }
  255. } else {
  256. target[prop] = source[prop]
  257. }
  258. }
  259. return target
  260. }
  261. /**
  262. * @description error提示
  263. * @param {*} err 错误内容
  264. */
  265. export function error(err) {
  266. // 开发环境才提示,生产环境不会提示
  267. if (process.env.NODE_ENV === 'development') {
  268. console.error(`uView提示:${err}`)
  269. }
  270. }
  271. /**
  272. * @description 打乱数组
  273. * @param {array} array 需要打乱的数组
  274. * @returns {array} 打乱后的数组
  275. */
  276. export function randomArray(array = []) {
  277. // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
  278. return array.sort(() => Math.random() - 0.5)
  279. }
  280. // padStart 的 polyfill,因为某些机型或情况,还无法支持es7的padStart,比如电脑版的微信小程序
  281. // 所以这里做一个兼容polyfill的兼容处理
  282. if (!String.prototype.padStart) {
  283. // 为了方便表示这里 fillString 用了ES6 的默认参数,不影响理解
  284. String.prototype.padStart = function(maxLength, fillString = ' ') {
  285. if (Object.prototype.toString.call(fillString) !== '[object String]') {
  286. throw new TypeError(
  287. 'fillString must be String'
  288. )
  289. }
  290. const str = this
  291. // 返回 String(str) 这里是为了使返回的值是字符串字面量,在控制台中更符合直觉
  292. if (str.length >= maxLength) return String(str)
  293. const fillLength = maxLength - str.length
  294. let times = Math.ceil(fillLength / fillString.length)
  295. while (times >>= 1) {
  296. fillString += fillString
  297. if (times === 1) {
  298. fillString += fillString
  299. }
  300. }
  301. return fillString.slice(0, fillLength) + str
  302. }
  303. }
  304. /**
  305. * @description 格式化时间
  306. * @param {String|Number} dateTime 需要格式化的时间戳
  307. * @param {String} fmt 格式化规则 yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合 默认yyyy-mm-dd
  308. * @returns {string} 返回格式化后的字符串
  309. */
  310. export function timeFormat(dateTime = null, formatStr = 'yyyy-mm-dd') {
  311. let date
  312. // 若传入时间为假值,则取当前时间
  313. if (!dateTime) {
  314. date = new Date()
  315. }
  316. // 若为unix秒时间戳,则转为毫秒时间戳(逻辑有点奇怪,但不敢改,以保证历史兼容)
  317. else if (/^\d{10}$/.test(dateTime.toString().trim())) {
  318. date = new Date(dateTime * 1000)
  319. }
  320. // 若用户传入字符串格式时间戳,new Date无法解析,需做兼容
  321. else if (typeof dateTime === 'string' && /^\d+$/.test(dateTime.trim())) {
  322. date = new Date(Number(dateTime))
  323. }
  324. // 其他都认为符合 RFC 2822 规范
  325. else {
  326. // 处理平台性差异,在Safari/Webkit中,new Date仅支持/作为分割符的字符串时间
  327. date = new Date(
  328. typeof dateTime === 'string'
  329. ? dateTime.replace(/-/g, '/')
  330. : dateTime
  331. )
  332. }
  333. const timeSource = {
  334. 'y': date.getFullYear().toString(), // 年
  335. 'm': (date.getMonth() + 1).toString().padStart(2, '0'), // 月
  336. 'd': date.getDate().toString().padStart(2, '0'), // 日
  337. 'h': date.getHours().toString().padStart(2, '0'), // 时
  338. 'M': date.getMinutes().toString().padStart(2, '0'), // 分
  339. 's': date.getSeconds().toString().padStart(2, '0') // 秒
  340. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  341. }
  342. for (const key in timeSource) {
  343. const [ret] = new RegExp(`${key}+`).exec(formatStr) || []
  344. if (ret) {
  345. // 年可能只需展示两位
  346. const beginIndex = key === 'y' && ret.length === 2 ? 2 : 0
  347. formatStr = formatStr.replace(ret, timeSource[key].slice(beginIndex))
  348. }
  349. }
  350. return formatStr
  351. }
  352. /**
  353. * @description 时间戳转为多久之前
  354. * @param {String|Number} timestamp 时间戳
  355. * @param {String|Boolean} format
  356. * 格式化规则如果为时间格式字符串,超出一定时间范围,返回固定的时间格式;
  357. * 如果为布尔值false,无论什么时间,都返回多久以前的格式
  358. * @returns {string} 转化后的内容
  359. */
  360. export function timeFrom(timestamp = null, format = 'yyyy-mm-dd') {
  361. if (timestamp == null) timestamp = Number(new Date())
  362. timestamp = parseInt(timestamp)
  363. // 判断用户输入的时间戳是秒还是毫秒,一般前端js获取的时间戳是毫秒(13位),后端传过来的为秒(10位)
  364. if (timestamp.toString().length == 10) timestamp *= 1000
  365. let timer = (new Date()).getTime() - timestamp
  366. timer = parseInt(timer / 1000)
  367. // 如果小于5分钟,则返回"刚刚",其他以此类推
  368. let tips = ''
  369. switch (true) {
  370. case timer < 300:
  371. tips = '刚刚'
  372. break
  373. case timer >= 300 && timer < 3600:
  374. tips = `${parseInt(timer / 60)}分钟前`
  375. break
  376. case timer >= 3600 && timer < 86400:
  377. tips = `${parseInt(timer / 3600)}小时前`
  378. break
  379. case timer >= 86400 && timer < 2592000:
  380. tips = `${parseInt(timer / 86400)}天前`
  381. break
  382. default:
  383. // 如果format为false,则无论什么时间戳,都显示xx之前
  384. if (format === false) {
  385. if (timer >= 2592000 && timer < 365 * 86400) {
  386. tips = `${parseInt(timer / (86400 * 30))}个月前`
  387. } else {
  388. tips = `${parseInt(timer / (86400 * 365))}年前`
  389. }
  390. } else {
  391. tips = timeFormat(timestamp, format)
  392. }
  393. }
  394. return tips
  395. }
  396. /**
  397. * @description 去除空格
  398. * @param String str 需要去除空格的字符串
  399. * @param String pos both(左右)|left|right|all 默认both
  400. */
  401. export function trim(str, pos = 'both') {
  402. str = String(str)
  403. if (pos == 'both') {
  404. return str.replace(/^\s+|\s+$/g, '')
  405. }
  406. if (pos == 'left') {
  407. return str.replace(/^\s*/, '')
  408. }
  409. if (pos == 'right') {
  410. return str.replace(/(\s*$)/g, '')
  411. }
  412. if (pos == 'all') {
  413. return str.replace(/\s+/g, '')
  414. }
  415. return str
  416. }
  417. /**
  418. * @description 对象转url参数
  419. * @param {object} data,对象
  420. * @param {Boolean} isPrefix,是否自动加上"?"
  421. * @param {string} arrayFormat 规则 indices|brackets|repeat|comma
  422. */
  423. export function queryParams(data = {}, isPrefix = true, arrayFormat = 'brackets') {
  424. const prefix = isPrefix ? '?' : ''
  425. const _result = []
  426. if (['indices', 'brackets', 'repeat', 'comma'].indexOf(arrayFormat) == -1) arrayFormat = 'brackets'
  427. for (const key in data) {
  428. const value = data[key]
  429. // 去掉为空的参数
  430. if (['', undefined, null].indexOf(value) >= 0) {
  431. continue
  432. }
  433. // 如果值为数组,另行处理
  434. if (value.constructor === Array) {
  435. // e.g. {ids: [1, 2, 3]}
  436. switch (arrayFormat) {
  437. case 'indices':
  438. // 结果: ids[0]=1&ids[1]=2&ids[2]=3
  439. for (let i = 0; i < value.length; i++) {
  440. _result.push(`${key}[${i}]=${value[i]}`)
  441. }
  442. break
  443. case 'brackets':
  444. // 结果: ids[]=1&ids[]=2&ids[]=3
  445. value.forEach((_value) => {
  446. _result.push(`${key}[]=${_value}`)
  447. })
  448. break
  449. case 'repeat':
  450. // 结果: ids=1&ids=2&ids=3
  451. value.forEach((_value) => {
  452. _result.push(`${key}=${_value}`)
  453. })
  454. break
  455. case 'comma':
  456. // 结果: ids=1,2,3
  457. let commaStr = ''
  458. value.forEach((_value) => {
  459. commaStr += (commaStr ? ',' : '') + _value
  460. })
  461. _result.push(`${key}=${commaStr}`)
  462. break
  463. default:
  464. value.forEach((_value) => {
  465. _result.push(`${key}[]=${_value}`)
  466. })
  467. }
  468. } else {
  469. _result.push(`${key}=${value}`)
  470. }
  471. }
  472. return _result.length ? prefix + _result.join('&') : ''
  473. }
  474. /**
  475. * 显示消息提示框
  476. * @param {String} title 提示的内容,长度与 icon 取值有关。
  477. * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000
  478. */
  479. export function toast(title, duration = 2000) {
  480. uni.showToast({
  481. title: String(title),
  482. icon: 'none',
  483. duration
  484. })
  485. }
  486. /**
  487. * @description 根据主题type值,获取对应的图标
  488. * @param {String} type 主题名称,primary|info|error|warning|success
  489. * @param {boolean} fill 是否使用fill填充实体的图标
  490. */
  491. export function type2icon(type = 'success', fill = false) {
  492. // 如果非预置值,默认为success
  493. if (['primary', 'info', 'error', 'warning', 'success'].indexOf(type) == -1) type = 'success'
  494. let iconName = ''
  495. // 目前(2019-12-12),info和primary使用同一个图标
  496. switch (type) {
  497. case 'primary':
  498. iconName = 'info-circle'
  499. break
  500. case 'info':
  501. iconName = 'info-circle'
  502. break
  503. case 'error':
  504. iconName = 'close-circle'
  505. break
  506. case 'warning':
  507. iconName = 'error-circle'
  508. break
  509. case 'success':
  510. iconName = 'checkmark-circle'
  511. break
  512. default:
  513. iconName = 'checkmark-circle'
  514. }
  515. // 是否是实体类型,加上-fill,在icon组件库中,实体的类名是后面加-fill的
  516. if (fill) iconName += '-fill'
  517. return iconName
  518. }
  519. /**
  520. * @description 数字格式化
  521. * @param {number|string} number 要格式化的数字
  522. * @param {number} decimals 保留几位小数
  523. * @param {string} decimalPoint 小数点符号
  524. * @param {string} thousandsSeparator 千分位符号
  525. * @returns {string} 格式化后的数字
  526. */
  527. export function priceFormat(number, decimals = 0, decimalPoint = '.', thousandsSeparator = ',') {
  528. number = (`${number}`).replace(/[^0-9+-Ee.]/g, '')
  529. const n = !isFinite(+number) ? 0 : +number
  530. const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  531. const sep = (typeof thousandsSeparator === 'undefined') ? ',' : thousandsSeparator
  532. const dec = (typeof decimalPoint === 'undefined') ? '.' : decimalPoint
  533. let s = ''
  534. s = (prec ? round(n, prec) + '' : `${Math.round(n)}`).split('.')
  535. const re = /(-?\d+)(\d{3})/
  536. while (re.test(s[0])) {
  537. s[0] = s[0].replace(re, `$1${sep}$2`)
  538. }
  539. if ((s[1] || '').length < prec) {
  540. s[1] = s[1] || ''
  541. s[1] += new Array(prec - s[1].length + 1).join('0')
  542. }
  543. return s.join(dec)
  544. }
  545. /**
  546. * @description 获取duration值
  547. * 如果带有ms或者s直接返回,如果大于一定值,认为是ms单位,小于一定值,认为是s单位
  548. * 比如以30位阈值,那么300大于30,可以理解为用户想要的是300ms,而不是想花300s去执行一个动画
  549. * @param {String|number} value 比如: "1s"|"100ms"|1|100
  550. * @param {boolean} unit 提示: 如果是false 默认返回number
  551. * @return {string|number}
  552. */
  553. export function getDuration(value, unit = true) {
  554. const valueNum = parseInt(value)
  555. if (unit) {
  556. if (/s$/.test(value)) return value
  557. return value > 30 ? `${value}ms` : `${value}s`
  558. }
  559. if (/ms$/.test(value)) return valueNum
  560. if (/s$/.test(value)) return valueNum > 30 ? valueNum : valueNum * 1000
  561. return valueNum
  562. }
  563. /**
  564. * @description 日期的月或日补零操作
  565. * @param {String} value 需要补零的值
  566. */
  567. export function padZero(value) {
  568. return `00${value}`.slice(-2)
  569. }
  570. /**
  571. * @description 在u-form的子组件内容发生变化,或者失去焦点时,尝试通知u-form执行校验方法
  572. * @param {*} instance
  573. * @param {*} event
  574. */
  575. export function formValidate(instance, event) {
  576. const formItem = $parent.call(instance, 'u-form-item')
  577. const form = $parent.call(instance, 'u-form')
  578. // 如果发生变化的input或者textarea等,其父组件中有u-form-item或者u-form等,就执行form的validate方法
  579. // 同时将form-item的pros传递给form,让其进行精确对象验证
  580. if (formItem && form) {
  581. form.validateField(formItem.prop, () => {}, event)
  582. }
  583. }
  584. /**
  585. * @description 获取某个对象下的属性,用于通过类似'a.b.c'的形式去获取一个对象的的属性的形式
  586. * @param {object} obj 对象
  587. * @param {string} key 需要获取的属性字段
  588. * @returns {*}
  589. */
  590. export function getProperty(obj, key) {
  591. if (typeof obj !== 'object' || null == obj) {
  592. return ''
  593. }
  594. if (typeof key !== 'string' || key === '') {
  595. return ''
  596. }
  597. if (key.indexOf('.') !== -1) {
  598. const keys = key.split('.')
  599. let firstObj = obj[keys[0]] || {}
  600. for (let i = 1; i < keys.length; i++) {
  601. if (firstObj) {
  602. firstObj = firstObj[keys[i]]
  603. }
  604. }
  605. return firstObj
  606. }
  607. return obj[key]
  608. }
  609. /**
  610. * @description 设置对象的属性值,如果'a.b.c'的形式进行设置
  611. * @param {object} obj 对象
  612. * @param {string} key 需要设置的属性
  613. * @param {string} value 设置的值
  614. */
  615. export function setProperty(obj, key, value) {
  616. if (typeof obj !== 'object' || null == obj) {
  617. return
  618. }
  619. // 递归赋值
  620. const inFn = function(_obj, keys, v) {
  621. // 最后一个属性key
  622. if (keys.length === 1) {
  623. _obj[keys[0]] = v
  624. return
  625. }
  626. // 0~length-1个key
  627. while (keys.length > 1) {
  628. const k = keys[0]
  629. if (!_obj[k] || (typeof _obj[k] !== 'object')) {
  630. _obj[k] = {}
  631. }
  632. const key = keys.shift()
  633. // 自调用判断是否存在属性,不存在则自动创建对象
  634. inFn(_obj[k], keys, v)
  635. }
  636. }
  637. if (typeof key !== 'string' || key === '') {
  638. } else if (key.indexOf('.') !== -1) { // 支持多层级赋值操作
  639. const keys = key.split('.')
  640. inFn(obj, keys, value)
  641. } else {
  642. obj[key] = value
  643. }
  644. }
  645. /**
  646. * @description 获取当前页面路径
  647. */
  648. export function page() {
  649. const pages = getCurrentPages()
  650. // 某些特殊情况下(比如页面进行redirectTo时的一些时机),pages可能为空数组
  651. return `/${pages[pages.length - 1].route || ''}`
  652. }
  653. /**
  654. * @description 获取当前路由栈实例数组
  655. */
  656. export function pages() {
  657. const pages = getCurrentPages()
  658. return pages
  659. }
  660. export default {
  661. range,
  662. getPx,
  663. sleep,
  664. os,
  665. sys,
  666. random,
  667. guid,
  668. $parent,
  669. addStyle,
  670. addUnit,
  671. deepClone,
  672. deepMerge,
  673. shallowMerge,
  674. error,
  675. randomArray,
  676. timeFormat,
  677. timeFrom,
  678. trim,
  679. queryParams,
  680. toast,
  681. type2icon,
  682. priceFormat,
  683. getDuration,
  684. padZero,
  685. formValidate,
  686. getProperty,
  687. setProperty,
  688. page,
  689. pages,
  690. // setConfig
  691. }