util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import CONSTANT from "@/constant";
  2. import { mobileReg } from "@/utils/tools/validate";
  3. import { getMiniAppUrl, isWxBrowser } from "@/utils/common";
  4. // 是否为空
  5. const isEmpty = val => {
  6. if (val instanceof Array) {
  7. if (val.length === 0){
  8. return true
  9. }
  10. } else if (val instanceof Object) {
  11. if (Object.keys(val).length == 0){
  12. return true
  13. }
  14. } else {
  15. if ( val === "null" || val === null || val === "undefined" || val === undefined || val === "" || JSON.stringify(val) == "[]"){
  16. return true
  17. }
  18. return false;
  19. }
  20. return false;
  21. };
  22. /**
  23. * 深拷贝对象
  24. * @param {要拷贝对象} obj
  25. */
  26. export const copyObject = obj => {
  27. let str,
  28. newobj = Array.isArray(obj) === true ? [] : {};
  29. if (typeof obj !== "object") {
  30. return;
  31. } else if (JSON) {
  32. (str = JSON.stringify(obj)), //系列化对象
  33. (newobj = JSON.parse(str)); //还原
  34. } else {
  35. for (let i in obj) {
  36. newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
  37. }
  38. }
  39. return newobj;
  40. };
  41. const numberFormat = (number, type) => {
  42. if (number > 10000) {
  43. let num = (number / 10000 + "").split(".");
  44. return `${num[0]}.${("" + num[1]).slice(0, 1)} 万`;
  45. } else {
  46. return number;
  47. }
  48. };
  49. // 截取图片上传字符串
  50. const imgSubstr = val => {
  51. if (isEmpty(val)) return [];
  52. if (isArray(val)) {
  53. return val.map(e => {
  54. if(e.indexOf("?") > -1){
  55. e = e.slice(0,e.indexOf("?"))
  56. }
  57. let index = e.indexOf("uploads/");
  58. e = e.substring(index);
  59. return e;
  60. });
  61. } else {
  62. if(e.indexOf("?") > -1){
  63. e = e.slice(0,e.indexOf("?"))
  64. }
  65. let index = val.indexOf("uploads/");
  66. return val.substring(index);
  67. }
  68. };
  69. // 是否为数组
  70. const isArray = arr => {
  71. return typeof arr == "object" && arr.constructor == Array;
  72. };
  73. // 是否为字符串
  74. const isString = str => {
  75. return typeof str == "string" && str.constructor == String;
  76. };
  77. // 是否为对象
  78. const isObject = obj => {
  79. return typeof obj == "object" && obj.constructor == Object;
  80. };
  81. // 是否为数字
  82. const isNumber = num => {
  83. return typeof num == "number" && num.constructor == Number;
  84. };
  85. // 是否为日期类型
  86. const isDate = date => {
  87. return typeof date == "object" && date.constructor == Date;
  88. };
  89. // 是否为函数
  90. const isFunction = obj => {
  91. return typeof obj == "object" && obj.constructor == Function;
  92. };
  93. const checkMobile = num => {
  94. return mobileReg.test(num);
  95. };
  96. const checkName = str => {
  97. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
  98. };
  99. //是否金额
  100. const isMoney = money =>{
  101. return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money)
  102. }
  103. /** *
  104. * 检查登录
  105. * @parmas query 拼接得参数对象
  106. * @parmas isFrist 为true时开头为&
  107. */
  108. export async function getCheckLogin() {
  109. let status = false;
  110. let token = uni.getStorageSync("token");
  111. if (token) {
  112. status = true;
  113. } else {
  114. // #ifdef H5
  115. if (isWxBrowser()) {
  116. let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
  117. console.log("option", option);
  118. // console.log('option', getMiniAppUrl(option, true))
  119. // return false
  120. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  121. getMiniAppUrl(option, true)
  122. )}`;
  123. } else {
  124. // uni.showToast({
  125. // title: '请用微信浏览器打开!',
  126. // icon: 'none',
  127. // mask: true
  128. // })
  129. }
  130. // #endif
  131. // #ifndef H5
  132. // #endif
  133. }
  134. return status;
  135. }
  136. export const floatFormat = (f, n) => {
  137. let m = Math.pow(10, n);
  138. return parseInt(f * m, 10) / m;
  139. };
  140. /** *
  141. * 对象参数转为url参数
  142. * @parmas query 拼接得参数对象
  143. * @parmas isFrist 为true时开头为&
  144. */
  145. export const parse = (query, isFrist = false) => {
  146. let str = Object.keys(query)
  147. .filter(key => !isEmpty(query[key]))
  148. .reduce((result, key) => {
  149. const value = query[key];
  150. // in查询特殊处理
  151. if (Array.isArray(value) && !isEmpty(value)) {
  152. return `${result}&${value.reduce(
  153. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  154. ""
  155. )}`;
  156. }
  157. // between查询做特殊处理
  158. if (typeof value === "object" && !isEmpty(value)) {
  159. const [start, end] = value;
  160. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  161. }
  162. return `${result}&${key}=${value}`;
  163. }, "");
  164. return isFrist ? str : str.replace(/^&/, "?");
  165. };
  166. /** *
  167. * 全局时间转换
  168. * @parmas num 时间戳默认为11位时间戳
  169. * @parmas fmt 默认转换的时间格式
  170. * @parmas all 为true时time为13位时间戳
  171. */
  172. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  173. num = all ? num : num * 1000;
  174. let date = new Date();
  175. date.setTime(num);
  176. let o = {
  177. "M+": date.getMonth() + 1,
  178. "D+": date.getDate(),
  179. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  180. "H+": date.getHours(),
  181. "m+": date.getMinutes(),
  182. "s+": date.getSeconds(),
  183. "q+": Math.floor((date.getMonth() + 3) / 3),
  184. S: date.getMilliseconds()
  185. };
  186. let week = {
  187. "0": "\u65e5",
  188. "1": "\u4e00",
  189. "2": "\u4e8c",
  190. "3": "\u4e09",
  191. "4": "\u56db",
  192. "5": "\u4e94",
  193. "6": "\u516d"
  194. };
  195. if (/(Y+)/.test(fmt)) {
  196. fmt = fmt.replace(
  197. RegExp.$1,
  198. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  199. );
  200. }
  201. if (/(E+)/.test(fmt)) {
  202. fmt = fmt.replace(
  203. RegExp.$1,
  204. (RegExp.$1.length > 1
  205. ? RegExp.$1.length > 2
  206. ? "\u661f\u671f"
  207. : "\u5468"
  208. : "") + week[date.getDay() + ""]
  209. );
  210. }
  211. for (let k in o) {
  212. if (new RegExp("(" + k + ")").test(fmt)) {
  213. fmt = fmt.replace(
  214. RegExp.$1,
  215. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  216. );
  217. }
  218. }
  219. return fmt;
  220. };
  221. /** *
  222. * 全局公共按钮跳转
  223. * @parmas item.funtion 为可执行函数
  224. * @parmas item.url 为跳转的路径
  225. * @parmas item.query 为跳转携带的参数
  226. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo 关闭当前页,跳转到指定页, 3为reLaunch, 4为switchTab
  227. */
  228. export const pageTo = item => {
  229. if (isNumber(item)) {
  230. uni.navigateBack({
  231. delta: item
  232. });
  233. }
  234. if (isString(item)) {
  235. uni.navigateTo({
  236. url: item
  237. });
  238. return false;
  239. }
  240. if (item.funtion) {
  241. item.funtion();
  242. }
  243. if (item.url) {
  244. let query = item.query ? parse(item.query) : "";
  245. let allUrl = `${item.url}${query}`;
  246. if (item.type == 2) {
  247. uni.redirectTo({ url: allUrl })
  248. } else if (item.type == 3) {
  249. uni.reLaunch({ url: allUrl })
  250. } else if (item.type == 4) {
  251. uni.setStorageSync("switchTabQuery", item.query);
  252. uni.switchTab({ url: item.url })
  253. } else {
  254. uni.navigateTo({ url: allUrl })
  255. }
  256. }
  257. };
  258. /** *
  259. * 是否登录
  260. */
  261. export const isLogin = () => {
  262. let token = uni.getStorageSync("token");
  263. if (token) {
  264. return true;
  265. }
  266. return false;
  267. };
  268. /**
  269. * 去重
  270. * 姜枫 2021.05.05
  271. * **/
  272. export const unique = (arr) => {
  273. for(var i=0; i<arr.length; i++){
  274. for(var j=i+1; j<arr.length; j++){
  275. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  276. arr.splice(j,1);
  277. j--;
  278. }
  279. }
  280. }
  281. return arr;
  282. };
  283. //#ifdef APP-PLUS
  284. const CLDialog=uni.requireNativePlugin("CL-Dialog")
  285. //#endif
  286. export const confirmModal = (item,okCallback=null,cancelCallback=null) => {
  287. let title = item.title || '提示'
  288. let content = item.content || '确认操作?'
  289. let okText = item.okText || '确认'
  290. let cancelText = item.cancelText || '取消'
  291. let cacelTextColor = '#999999'
  292. let okTextColor = '#38ADFF'
  293. let singer = item.singer || false
  294. //#ifdef APP-PLUS
  295. let options={
  296. title:title,//标题 (可选)
  297. con:content,//内容(可选)但是标题和内容至少选择一个
  298. okTitle:okText,//确认按钮文字(可选)
  299. cancleTitle:cancelText,//取消按钮文字(可选)
  300. okTextColor:"#38ADFF",//确认按钮颜色(可选)
  301. cancleTextColor:"#999999",//取消按钮颜色(可选)
  302. singer:singer,//是否只显示确认按钮,默认false(可选)
  303. textAlign:"center",//对齐方式 //left居左,center居中,right 居右 默认居中
  304. conColor:"",
  305. bgColor:"#FFFFFF",//自定义弹框颜色
  306. titleColor:"#3d3d3d"//自定义title颜色
  307. }
  308. CLDialog.show(options,()=>{
  309. if(okCallback!=null){
  310. okCallback()
  311. }
  312. },()=>{
  313. if(cancelCallback!=null){
  314. cancelCallback()
  315. }
  316. })
  317. //#endif
  318. // #ifdef MP-WEIXIN
  319. uni.showModal({
  320. title: title,
  321. content: content,
  322. showCancel: true,
  323. cancelText: cancelText,
  324. cancelColor: cacelTextColor,
  325. confirmText: okText,
  326. confirmColor: okTextColor,
  327. success: function (res) {
  328. if (res.confirm) {
  329. if(okCallback!=null){
  330. okCallback()
  331. }
  332. } else if (res.cancel) {
  333. if(cancelCallback!=null){
  334. cancelCallback()
  335. }
  336. }
  337. }
  338. })
  339. //#endif
  340. }
  341. //判断是否有扫码的条件
  342. export const isScanEnv = () =>{
  343. let isScanEnv = false
  344. //#ifdef APP-PLUS
  345. if(plus.device.vendor == 'SUNMI'){
  346. isScanEnv = true
  347. }
  348. if(plus.device.vendor == 'Newland'){
  349. isScanEnv = true
  350. }
  351. //#endif
  352. return isScanEnv
  353. }
  354. //加
  355. export const add = (arg1, arg2) => {
  356. var r1, r2, m, n;
  357. try {
  358. r1 = arg1.toString().split(".")[1].length
  359. } catch (e) {
  360. r1 = 0
  361. }
  362. try {
  363. r2 = arg2.toString().split(".")[1].length
  364. } catch (e) {
  365. r2 = 0
  366. }
  367. m = Math.pow(10, Math.max(r1, r2))
  368. n = (r1 >= r2) ? r1 : r2;
  369. return ((arg1 * m + arg2 * m) / m).toFixed(n);
  370. }
  371. //减
  372. export const sub = (arg1, arg2) => {
  373. var re1, re2, m, n;
  374. try {
  375. re1 = arg1.toString().split(".")[1].length;
  376. } catch (e) {
  377. re1 = 0;
  378. }
  379. try {
  380. re2 = arg2.toString().split(".")[1].length;
  381. } catch (e) {
  382. re2 = 0;
  383. }
  384. m = Math.pow(10, Math.max(re1, re2));
  385. n = (re1 >= re2) ? re1 : re2;
  386. return ((arg1 * m - arg2 * m) / m).toFixed(n);
  387. }
  388. //乘
  389. export const mul = (arg1, arg2) => {
  390. var m = 0;
  391. var s1 = arg1.toString();
  392. var s2 = arg2.toString();
  393. try {
  394. m += s1.split(".")[1].length;
  395. } catch (e) {}
  396. try {
  397. m += s2.split(".")[1].length;
  398. } catch (e) {}
  399. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
  400. }
  401. // 除数,被除数, 保留的小数点后的位数
  402. export const div = (arg1,arg2,digit) =>{
  403. var t1=0,t2=0,r1,r2;
  404. try{t1=arg1.toString().split(".")[1].length}catch(e){}
  405. try{t2=arg2.toString().split(".")[1].length}catch(e){}
  406. r1=Number(arg1.toString().replace(".",""))
  407. r2=Number(arg2.toString().replace(".",""))
  408. //获取小数点后的计算值
  409. var result= ((r1/r2)*Math.pow(10,t2-t1)).toString()
  410. var result2=result.split(".")[1];
  411. result2=result2.substring(0,digit>result2.length?result2.length:digit);
  412. return Number(result.split(".")[0]+"."+result2);
  413. }
  414. export default {
  415. isEmpty,
  416. copyObject,
  417. imgSubstr,
  418. isArray,
  419. parse,
  420. checkMobile,
  421. checkName,
  422. $formatDate,
  423. floatFormat,
  424. pageTo,
  425. isLogin,
  426. getCheckLogin,
  427. numberFormat,
  428. isString,
  429. unique,
  430. isMoney,
  431. confirmModal,
  432. isScanEnv,
  433. add,
  434. sub,
  435. mul,
  436. div
  437. };