util.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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) return true;
  8. } else if (val instanceof Object) {
  9. if (!Object.keys(val).length) return true;
  10. } else {
  11. if (
  12. val === "null" ||
  13. val === null ||
  14. val === "undefined" ||
  15. val === undefined ||
  16. val === ""
  17. )
  18. return true;
  19. return false;
  20. }
  21. return false;
  22. };
  23. /**
  24. * 深拷贝对象
  25. * @param {要拷贝对象} obj
  26. */
  27. export const copyObject = obj => {
  28. let str,
  29. newobj = Array.isArray(obj) === true ? [] : {};
  30. if (typeof obj !== "object") {
  31. return;
  32. } else if (JSON) {
  33. (str = JSON.stringify(obj)), //系列化对象
  34. (newobj = JSON.parse(str)); //还原
  35. } else {
  36. for (let i in obj) {
  37. newobj[i] = typeof obj[i] === "object" ? copyObject(obj[i]) : obj[i];
  38. }
  39. }
  40. return newobj;
  41. };
  42. const numberFormat = (number, type) => {
  43. if (number > 10000) {
  44. let num = (number / 10000 + "").split(".");
  45. return `${num[0]}.${("" + num[1]).slice(0, 1)} 万`;
  46. } else {
  47. return number;
  48. }
  49. };
  50. // 截取图片上传字符串
  51. const imgSubstr = val => {
  52. if (isEmpty(val)) return [];
  53. if (isArray(val)) {
  54. return val.map(e => {
  55. if(e.indexOf("?") > -1){
  56. e = e.slice(0,e.indexOf("?"))
  57. }
  58. let index = e.indexOf("uploads/");
  59. e = e.substring(index);
  60. return e;
  61. });
  62. } else {
  63. if(e.indexOf("?") > -1){
  64. e = e.slice(0,e.indexOf("?"))
  65. }
  66. let index = val.indexOf("uploads/");
  67. return val.substring(index);
  68. }
  69. };
  70. // 是否为数组
  71. const isArray = arr => {
  72. return typeof arr == "object" && arr.constructor == Array;
  73. };
  74. // 是否为字符串
  75. const isString = str => {
  76. return typeof str == "string" && str.constructor == String;
  77. };
  78. // 是否为对象
  79. const isObject = obj => {
  80. return typeof obj == "object" && obj.constructor == Object;
  81. };
  82. // 是否为数字
  83. const isNumber = num => {
  84. return typeof num == "number" && num.constructor == Number;
  85. };
  86. // 是否为日期类型
  87. const isDate = date => {
  88. return typeof date == "object" && date.constructor == Date;
  89. };
  90. // 是否为函数
  91. const isFunction = obj => {
  92. return typeof obj == "object" && obj.constructor == Function;
  93. };
  94. const checkMobile = num => {
  95. return mobileReg.test(num);
  96. };
  97. const checkName = str => {
  98. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
  99. };
  100. //是否金额
  101. const isMoney = money =>{
  102. return /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(money)
  103. }
  104. /** *
  105. * 检查登录
  106. * @parmas query 拼接得参数对象
  107. * @parmas isFrist 为true时开头为&
  108. */
  109. export async function getCheckLogin() {
  110. let status = false;
  111. let token = uni.getStorageSync("token");
  112. if (token) {
  113. status = true;
  114. } else {
  115. // #ifdef H5
  116. if (isWxBrowser()) {
  117. let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
  118. console.log("option", option);
  119. // console.log('option', getMiniAppUrl(option, true))
  120. // return false
  121. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  122. getMiniAppUrl(option, true)
  123. )}`;
  124. } else {
  125. // uni.showToast({
  126. // title: '请用微信浏览器打开!',
  127. // icon: 'none',
  128. // mask: true
  129. // })
  130. }
  131. // #endif
  132. // #ifndef H5
  133. // #endif
  134. }
  135. return status;
  136. }
  137. export const floatFormat = (f, n) => {
  138. let m = Math.pow(10, n);
  139. return parseInt(f * m, 10) / m;
  140. };
  141. /** *
  142. * 对象参数转为url参数
  143. * @parmas query 拼接得参数对象
  144. * @parmas isFrist 为true时开头为&
  145. */
  146. export const parse = (query, isFrist = false) => {
  147. let str = Object.keys(query)
  148. .filter(key => !isEmpty(query[key]))
  149. .reduce((result, key) => {
  150. const value = query[key];
  151. // in查询特殊处理
  152. if (Array.isArray(value) && !isEmpty(value)) {
  153. return `${result}&${value.reduce(
  154. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  155. ""
  156. )}`;
  157. }
  158. // between查询做特殊处理
  159. if (typeof value === "object" && !isEmpty(value)) {
  160. const [start, end] = value;
  161. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  162. }
  163. return `${result}&${key}=${value}`;
  164. }, "");
  165. return isFrist ? str : str.replace(/^&/, "?");
  166. };
  167. /** *
  168. * 全局时间转换
  169. * @parmas num 时间戳默认为11位时间戳
  170. * @parmas fmt 默认转换的时间格式
  171. * @parmas all 为true时time为13位时间戳
  172. */
  173. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  174. num = all ? num : num * 1000;
  175. let date = new Date();
  176. date.setTime(num);
  177. let o = {
  178. "M+": date.getMonth() + 1,
  179. "D+": date.getDate(),
  180. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  181. "H+": date.getHours(),
  182. "m+": date.getMinutes(),
  183. "s+": date.getSeconds(),
  184. "q+": Math.floor((date.getMonth() + 3) / 3),
  185. S: date.getMilliseconds()
  186. };
  187. let week = {
  188. "0": "\u65e5",
  189. "1": "\u4e00",
  190. "2": "\u4e8c",
  191. "3": "\u4e09",
  192. "4": "\u56db",
  193. "5": "\u4e94",
  194. "6": "\u516d"
  195. };
  196. if (/(Y+)/.test(fmt)) {
  197. fmt = fmt.replace(
  198. RegExp.$1,
  199. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  200. );
  201. }
  202. if (/(E+)/.test(fmt)) {
  203. fmt = fmt.replace(
  204. RegExp.$1,
  205. (RegExp.$1.length > 1
  206. ? RegExp.$1.length > 2
  207. ? "\u661f\u671f"
  208. : "\u5468"
  209. : "") + week[date.getDay() + ""]
  210. );
  211. }
  212. for (let k in o) {
  213. if (new RegExp("(" + k + ")").test(fmt)) {
  214. fmt = fmt.replace(
  215. RegExp.$1,
  216. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  217. );
  218. }
  219. }
  220. return fmt;
  221. };
  222. /** *
  223. * 全局公共按钮跳转
  224. * @parmas item.funtion 为可执行函数
  225. * @parmas item.url 为跳转的路径
  226. * @parmas item.query 为跳转携带的参数
  227. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo, 3为reLaunch, 4为switchTab
  228. */
  229. export const pageTo = item => {
  230. if (isNumber(item)) {
  231. uni.navigateBack({
  232. delta: item
  233. });
  234. }
  235. if (isString(item)) {
  236. uni.navigateTo({
  237. url: item
  238. });
  239. return false;
  240. }
  241. if (item.funtion) {
  242. item.funtion();
  243. }
  244. if (item.url) {
  245. let query = item.query ? parse(item.query) : "";
  246. let allUrl = `${item.url}${query}`;
  247. if (item.type == 2) {
  248. uni.redirectTo({
  249. url: allUrl
  250. });
  251. } else if (item.type == 3) {
  252. uni.reLaunch({
  253. url: allUrl
  254. });
  255. } else if (item.type == 4) {
  256. console.log("switchTab", item.query);
  257. uni.setStorageSync("switchTabQuery", item.query);
  258. uni.switchTab({
  259. url: item.url
  260. });
  261. } else {
  262. uni.navigateTo({
  263. url: allUrl
  264. });
  265. }
  266. }
  267. };
  268. /** *
  269. * 是否登录
  270. */
  271. export const isLogin = () => {
  272. let token = uni.getStorageSync("token");
  273. if (token) {
  274. return true;
  275. }
  276. return false;
  277. };
  278. /**
  279. * 去重
  280. * 姜枫 2021.05.05
  281. * **/
  282. export const unique = (arr) => {
  283. for(var i=0; i<arr.length; i++){
  284. for(var j=i+1; j<arr.length; j++){
  285. if(arr[i].classId==arr[j].classId){ //第一个等同于第二个,splice方法删除第二个
  286. arr.splice(j,1);
  287. j--;
  288. }
  289. }
  290. }
  291. return arr;
  292. };
  293. export default {
  294. isEmpty,
  295. copyObject,
  296. imgSubstr,
  297. isArray,
  298. parse,
  299. checkMobile,
  300. checkName,
  301. $formatDate,
  302. floatFormat,
  303. pageTo,
  304. isLogin,
  305. getCheckLogin,
  306. numberFormat,
  307. isString,
  308. unique,
  309. isMoney
  310. };