index.js 23 KB

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