index.js 22 KB

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