index.js 25 KB

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