util.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. export default {
  284. isEmpty,
  285. copyObject,
  286. imgSubstr,
  287. isArray,
  288. parse,
  289. checkMobile,
  290. checkName,
  291. $formatDate,
  292. floatFormat,
  293. pageTo,
  294. isLogin,
  295. getCheckLogin,
  296. numberFormat,
  297. isString,
  298. unique,
  299. isMoney
  300. };