grace.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. link : http://grace.hcoder.net
  3. author : 刘海君 5213606@qq.com
  4. verson : 1.01
  5. last update date : 2020-03-19
  6. */
  7. module.exports = {
  8. // 版本检查
  9. verson : function(){
  10. var currentVersion = '1.0';
  11. console.log(currentVersion);
  12. },
  13. // --- 页面跳转相关 ---
  14. // 页面跳转
  15. navigate:function (url, type, success, fail, complete) {
  16. if(!type){type = 'navigateTo';}
  17. if(!success){success = function(){};}
  18. if(!fail){fail = function(){};}
  19. if(!complete){complete = function(){};}
  20. switch(type){
  21. case 'navigateTo' :
  22. uni.navigateTo({url:url, success:success, fail:fail, complete:complete});
  23. break;
  24. case 'redirectTo' :
  25. uni.redirectTo({url:url, success:success, fail:fail, complete:complete});
  26. break;
  27. case 'switchTab' :
  28. uni.switchTab({url:url, success:success, fail:fail, complete:complete});
  29. break;
  30. case 'reLaunch' :
  31. uni.reLaunch({url:url, success:success, fail:fail, complete:complete});
  32. break;
  33. }
  34. },
  35. // 返回
  36. back:function(delta){
  37. if(!delta){delta = 1;}
  38. uni.navigateBack({delta:delta});
  39. },
  40. // --- 网络请求 ---
  41. // get
  42. get : function(url, data, headers, success, fail){
  43. if(!fail){fail = () => {this.msg("网络请求失败");}}
  44. if(!headers){headers={};}
  45. if(this.__before != null){this.__before(); this.__before = null;}
  46. uni.request({
  47. url : url,
  48. data : data,
  49. method : "GET",
  50. dataType : "json",
  51. header : headers,
  52. success : (res) => {success(res.data);},
  53. fail : fail,
  54. complete : () => {if(this.__after != null){this.__after(); this.__after = null;}}
  55. });
  56. },
  57. // post
  58. post : function(url, data, contentType, headers, success, fail){
  59. if(!fail){fail = () => {this.msg("网络请求失败");}}
  60. if(!headers){headers={};}
  61. if(!contentType){contentType = 'form';}
  62. if(this.__before != null){this.__before(); this.__before = null;}
  63. switch(contentType){
  64. case "form" :
  65. headers['content-type'] = 'application/x-www-form-urlencoded';
  66. break;
  67. case "json" :
  68. headers['content-type'] = 'application/json';
  69. break;
  70. default :
  71. headers['content-type'] = 'application/x-www-form-urlencoded';
  72. }
  73. uni.request({
  74. url : url,
  75. data : data,
  76. method : "POST",
  77. dataType : "json",
  78. header : headers,
  79. success : (res) => {success(res.data);},
  80. fail : fail,
  81. complete : () => {if(this.__after != null){this.__after(); this.__after = null;}}
  82. });
  83. },
  84. // 请求前置函数
  85. __before : null,
  86. setBefore : function(func){
  87. this.__before = func;
  88. },
  89. // 请求后置函数
  90. __after : null,
  91. setAfter : function(func){
  92. this.__after = func;
  93. },
  94. // --- 数据缓存 ---
  95. setStorage : function(data){
  96. try {
  97. for(let k in data){uni.setStorageSync(k, data[k]+'');}
  98. return true;
  99. } catch (e){return false;}
  100. },
  101. getStorage : function(keyName){
  102. try {
  103. var tmpVal = uni.getStorageSync(keyName);
  104. if(tmpVal == ''){return false;}
  105. return tmpVal;
  106. } catch (e){return false;}
  107. },
  108. removeStorage : function(keyName){
  109. try {
  110. uni.removeStorageSync(keyName);
  111. return true;
  112. } catch (e){return false;}
  113. },
  114. clearStorage : function(){
  115. try { uni.clearStorageSync(); } catch (e) {}
  116. },
  117. // --- 图片相关 ---
  118. chooseImgs : function(sets, success, fail, complete) {
  119. if(!sets.count){sets.count = 1;}
  120. if(!sets.sizeType){sets.sizeType = ['original', 'compressed'];}
  121. if(!sets.sourceType){sets.sourceType = ['album', 'camera'];}
  122. uni.chooseImage({
  123. count: sets.count, //默认9
  124. sizeType: sets.sizeType, //可以指定是原图还是压缩图,默认二者都有
  125. sourceType: sets.sourceType, //从相册选择
  126. success:(res) => {success(res.tempFilePaths);},
  127. fail: (e) => { if(fail){fail(e);}},
  128. complete: (e) => { if(complete){complete(e);}}
  129. });
  130. },
  131. getImageInfo : function(imgUrl, success, fail, complete){
  132. uni.getImageInfo({
  133. src: imgUrl,
  134. success: function (info) {success(info);},
  135. fail: (e) => { if(fail){fail(e);}},
  136. complete: (e) => { if(complete){complete(e);}}
  137. });
  138. },
  139. previewImage : function (items, currentImg) {
  140. uni.previewImage({ urls: items, current:currentImg});
  141. },
  142. // --- 系统信息 ---
  143. system : function () {
  144. try {
  145. var res = uni.getSystemInfoSync();
  146. var iPhoneXBottom = 0;
  147. res.model = res.model.replace(' ', '');
  148. res.model = res.model.toLowerCase();
  149. if(res.model.indexOf('iphonex') != -1 || res.model.indexOf('iphone11') != -1){
  150. res.iPhoneXBottomHeightRpx = 50;
  151. res.iPhoneXBottomHeightPx = uni.upx2px(50);
  152. }else{
  153. res.iPhoneXBottomHeightRpx = 0;
  154. res.iPhoneXBottomHeightPx = 0;
  155. }
  156. return res;
  157. } catch (e){
  158. return null;
  159. }
  160. },
  161. // --- 消息弹框 ---
  162. msg : function(msg){uni.showToast({title:msg, icon:"none"});},
  163. showLoading : function (title) {uni.showLoading({ title:title });},
  164. // --- 导航条设置 ---
  165. setNavBar : function(sets){
  166. if(sets.title){uni.setNavigationBarTitle({title:sets.title});}
  167. if(sets.color){
  168. uni.setNavigationBarColor({
  169. frontColor: sets.color.frontColor,
  170. backgroundColor:sets.color.backgroundColor,
  171. animation: {
  172. duration: 400,
  173. timingFunc: 'easeIn'
  174. }
  175. });
  176. }
  177. if(sets.loading){
  178. uni.showNavigationBarLoading();
  179. }else{
  180. uni.hideNavigationBarLoading();
  181. }
  182. },
  183. // --- 元素选择 ---
  184. // 单个元素选择
  185. select : function (selector, callBack) {
  186. uni.createSelectorQuery().select(selector).boundingClientRect().exec((res)=>{callBack(res[0]);});
  187. },
  188. // 多个元素获取
  189. selectAll : function (selector, callBack) {
  190. uni.createSelectorQuery().selectAll(selector).boundingClientRect().exec((res)=>{callBack(res[0]);});
  191. },
  192. // --- 数组操作 ---
  193. // 数组合并
  194. arrayConcat : function(){
  195. var tmpArr = [];
  196. for(let i = 0; i < arguments.length; i++){tmpArr = tmpArr.concat(arguments[i]);}
  197. return tmpArr;
  198. },
  199. arrayDrop : function(array, index, howmany){
  200. if(!index){index = 0;}
  201. if(!howmany){howmany = 1;}
  202. array.splice(index, howmany);
  203. return array;
  204. },
  205. arrayIndexOf : function(arr, needFind){
  206. var index = -1;
  207. for(let i = 0; i < arr.length; i++){
  208. if(arr[i] == needFind){index = i; return i;}
  209. }
  210. return index;
  211. },
  212. arrayDifference : function(a, b){
  213. const set = new Set(b);
  214. return a.filter(x => !set.has(x));
  215. },
  216. arrayShuffle : function (arr) {
  217. let l = arr.length;
  218. while (l) {
  219. const i = Math.floor(Math.random() * l--);
  220. [arr[l], arr[i]] = [arr[i], arr[l]];
  221. console.log(i);
  222. }
  223. return arr;
  224. },
  225. arraySum: function(arr){
  226. return arr.reduce((acc, val) => acc + val, 0);
  227. },
  228. arrayAvg: function(arr){
  229. return arr.reduce((acc, val) => acc + val, 0) / arr.length;
  230. },
  231. arrayEach : function(arr, fun){
  232. for(let i = 0; i < arr.length; i++) {fun(arr[i], i);}
  233. },
  234. // 2数之间的随机数
  235. random : function(min, max){
  236. switch(arguments.length){
  237. case 1:
  238. return parseInt(Math.random() * min + 1,10);
  239. break;
  240. case 2:
  241. return parseInt(Math.random() * (max - min + 1 ) + min, 10);
  242. break;
  243. default:
  244. return 0;
  245. }
  246. },
  247. // UUID
  248. uuid : function(len){
  249. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  250. var uuid = [], i;
  251. if(len){
  252. for (i = 0; i < len; i++){uuid[i] = chars[0 | Math.random() * chars.length];}
  253. }else{
  254. var r;
  255. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  256. uuid[14] = '4';
  257. for(i = 0; i < 36; i++){
  258. if (!uuid[i]){
  259. r = 0 | Math.random() * 16;
  260. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  261. }
  262. }
  263. }
  264. return uuid.join('');
  265. },
  266. // --- 日期时间 ---
  267. now : function (type, addTime) {
  268. var dateObj = new Date();
  269. var cTime = dateObj.getTime();
  270. if(addTime){cTime += addTime;}
  271. if(!type){type = 'number';}
  272. if(type == 'number'){return cTime;}
  273. return this.toDate(cTime / 1000, 'str');
  274. },
  275. // 时间戳转 YY-mm-dd HH:ii:ss
  276. toDate : function(timeStamp, returnType){
  277. timeStamp = parseInt(timeStamp);
  278. var date = new Date();
  279. if(timeStamp < 90000000000 ){
  280. date.setTime(timeStamp * 1000);
  281. }else{
  282. date.setTime(timeStamp );
  283. }
  284. var y = date.getFullYear();
  285. var m = date.getMonth() + 1;
  286. m = m < 10 ? ('0' + m) : m;
  287. var d = date.getDate();
  288. d = d < 10 ? ('0' + d) : d;
  289. var h = date.getHours();
  290. h = h < 10 ? ('0' + h) : h;
  291. var minute = date.getMinutes();
  292. var second = date.getSeconds();
  293. minute = minute < 10 ? ('0' + minute) : minute;
  294. second = second < 10 ? ('0' + second) : second;
  295. if(returnType == 'str'){return y + '-' + m + '-' + d + ' '+ h +':' + minute + ':' + second;}
  296. return [y, m, d, h, minute, second];
  297. },
  298. // 字符串转时间戳
  299. toTimeStamp : function(timeStamp){
  300. var reg = /^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
  301. var res = timeStamp.match(reg);
  302. if (res == null){
  303. var reg2 = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/;
  304. var res2 = timeStamp.match(reg2);
  305. if(res2 == null){ console.log('时间格式错误 E001'); return false;}
  306. var year = parseInt(res2[3]);
  307. var month = parseInt(res2[1]);
  308. var day = parseInt(res2[2]);
  309. var h = parseInt(res2[4]);
  310. var i = parseInt(res2[5]);
  311. var s = parseInt(res2[6]);
  312. }else{
  313. var year = parseInt(res[1]);
  314. var month = parseInt(res[2]);
  315. var day = parseInt(res[3]);
  316. var h = parseInt(res[4]);
  317. var i = parseInt(res[5]);
  318. var s = parseInt(res[6]);
  319. }
  320. if (year < 1000) { console.log('时间格式错误'); return false; }
  321. if (h < 0 || h > 24) { console.log('时间格式错误'); return false; }
  322. if (i < 0 || i > 60) { console.log('时间格式错误'); return false; }
  323. if (s < 0 || s > 60) { console.log('时间格式错误'); return false; }
  324. return Date.parse(new Date(year, month - 1, day, h, i, s));
  325. },
  326. // 根据时间戳计算多少分钟/小时/天之前
  327. fromTime : function (time){
  328. if(time < 90000000000 ){time *= 1000;}
  329. var timer = new Date().getTime() - time;
  330. timer = parseInt(timer / 1000);
  331. if(timer < 180){
  332. return '刚刚';
  333. }else if(timer >= 180 && timer < 3600){
  334. return parseInt(timer / 60) + '分钟前';
  335. }else if(timer >= 3600 && timer < 86400){
  336. return parseInt(timer / 3600) + '小时前';
  337. }else if(timer >= 86400 && timer < 2592000){
  338. return parseInt(timer / 86400) + '天前';
  339. }else{
  340. return this.toDate(time, 'str');
  341. }
  342. },
  343. // 延迟操作
  344. delay:function (timer, func){
  345. return setTimeout(func, timer);
  346. },
  347. // 间隔指定时间循环某个函数
  348. interval:function (timer, func){
  349. return setInterval(func, timer);
  350. },
  351. // 对象操作
  352. assign : function (obj, key, val) {obj[key] = val;},
  353. removeByKey : function (obj, key) {delete obj[key];},
  354. each : function(obj, func){
  355. for(let k in obj){func(k, obj[k]);}
  356. },
  357. isEmptyObj : function(obj){return JSON.stringify(obj) === '{}';}
  358. }