index.js 23 KB

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