index.js 22 KB

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