index.js 21 KB

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