index.js 23 KB

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