util.js 7.0 KB

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