util.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. 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 isDate = date => {
  82. return typeof date == "object" && date.constructor == Date;
  83. };
  84. // 是否为函数
  85. const isFunction = obj => {
  86. return typeof obj == "object" && obj.constructor == Function;
  87. };
  88. const checkMobile = num => {
  89. return mobileReg.test(num);
  90. };
  91. const checkName = str => {
  92. return /^[\u4E00-\u9FA5A-Za-z\s]+(·[\u4E00-\u9FA5A-Za-z]+)*$/.test(str);
  93. };
  94. /** *
  95. * 检查登录
  96. * @parmas query 拼接得参数对象
  97. * @parmas isFrist 为true时开头为&
  98. */
  99. export async function getCheckLogin() {
  100. let status = false;
  101. let token = uni.getStorageSync("token");
  102. if (token) {
  103. status = true;
  104. } else {
  105. // #ifdef H5
  106. if (isWxBrowser()) {
  107. let option = JSON.parse(uni.getStorageSync("currentQuery")) || {};
  108. console.log("option", option);
  109. // console.log('option', getMiniAppUrl(option, true))
  110. // return false
  111. location.href = `${CONSTANT.hostUrl}/auth/prepare?url=${encodeURIComponent(
  112. getMiniAppUrl(option, true)
  113. )}`;
  114. } else {
  115. // uni.showToast({
  116. // title: '请用微信浏览器打开!',
  117. // icon: 'none',
  118. // mask: true
  119. // })
  120. }
  121. // #endif
  122. // #ifndef H5
  123. // #endif
  124. }
  125. return status;
  126. }
  127. export const floatFormat = (f, n) => {
  128. let m = Math.pow(10, n);
  129. return parseInt(f * m, 10) / m;
  130. };
  131. /** *
  132. * 对象参数转为url参数
  133. * @parmas query 拼接得参数对象
  134. * @parmas isFrist 为true时开头为&
  135. */
  136. export const parse = (query, isFrist = false) => {
  137. let str = Object.keys(query)
  138. .filter(key => !isEmpty(query[key]))
  139. .reduce((result, key) => {
  140. const value = query[key];
  141. // in查询特殊处理
  142. if (Array.isArray(value) && !isEmpty(value)) {
  143. return `${result}&${value.reduce(
  144. (val, cVal) => `${val ? `${val}&` : val}${key}=${cVal}`,
  145. ""
  146. )}`;
  147. }
  148. // between查询做特殊处理
  149. if (typeof value === "object" && !isEmpty(value)) {
  150. const [start, end] = value;
  151. return `${result}&${key}[]=${start}&${key}[]=${end}`;
  152. }
  153. return `${result}&${key}=${value}`;
  154. }, "");
  155. return isFrist ? str : str.replace(/^&/, "?");
  156. };
  157. /** *
  158. * 全局时间转换
  159. * @parmas num 时间戳默认为11位时间戳
  160. * @parmas fmt 默认转换的时间格式
  161. * @parmas all 为true时time为13位时间戳
  162. */
  163. export const $formatDate = (num, fmt = "YYYY-MM-DD HH:mm", all) => {
  164. num = all ? num : num * 1000;
  165. let date = new Date();
  166. date.setTime(num);
  167. let o = {
  168. "M+": date.getMonth() + 1,
  169. "D+": date.getDate(),
  170. "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12,
  171. "H+": date.getHours(),
  172. "m+": date.getMinutes(),
  173. "s+": date.getSeconds(),
  174. "q+": Math.floor((date.getMonth() + 3) / 3),
  175. S: date.getMilliseconds()
  176. };
  177. let week = {
  178. "0": "\u65e5",
  179. "1": "\u4e00",
  180. "2": "\u4e8c",
  181. "3": "\u4e09",
  182. "4": "\u56db",
  183. "5": "\u4e94",
  184. "6": "\u516d"
  185. };
  186. if (/(Y+)/.test(fmt)) {
  187. fmt = fmt.replace(
  188. RegExp.$1,
  189. (date.getFullYear() + "").substr(4 - RegExp.$1.length)
  190. );
  191. }
  192. if (/(E+)/.test(fmt)) {
  193. fmt = fmt.replace(
  194. RegExp.$1,
  195. (RegExp.$1.length > 1
  196. ? RegExp.$1.length > 2
  197. ? "\u661f\u671f"
  198. : "\u5468"
  199. : "") + week[date.getDay() + ""]
  200. );
  201. }
  202. for (let k in o) {
  203. if (new RegExp("(" + k + ")").test(fmt)) {
  204. fmt = fmt.replace(
  205. RegExp.$1,
  206. RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
  207. );
  208. }
  209. }
  210. return fmt;
  211. };
  212. /** *
  213. * 全局公共按钮跳转
  214. * @parmas item.funtion 为可执行函数
  215. * @parmas item.url 为跳转的路径
  216. * @parmas item.query 为跳转携带的参数
  217. * @parmas item.type 为跳转调用的函数 1为navigateTo, 2为redirectTo, 3为reLaunch, 4为switchTab
  218. */
  219. export const pageTo = item => {
  220. if (isNumber(item)) {
  221. uni.navigateBack({
  222. delta: item
  223. });
  224. }
  225. if (isString(item)) {
  226. uni.navigateTo({
  227. url: item
  228. });
  229. return false;
  230. }
  231. if (item.funtion) {
  232. item.funtion();
  233. }
  234. if (item.url) {
  235. let query = item.query ? parse(item.query) : "";
  236. let allUrl = `${item.url}${query}`;
  237. if (item.type == 2) {
  238. uni.redirectTo({
  239. url: allUrl
  240. });
  241. } else if (item.type == 3) {
  242. uni.reLaunch({
  243. url: allUrl
  244. });
  245. } else if (item.type == 4) {
  246. console.log("switchTab", item.query);
  247. uni.setStorageSync("switchTabQuery", item.query);
  248. uni.switchTab({
  249. url: item.url
  250. });
  251. } else {
  252. uni.navigateTo({
  253. url: allUrl
  254. });
  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. export default {
  269. isEmpty,
  270. copyObject,
  271. imgSubstr,
  272. isArray,
  273. parse,
  274. checkMobile,
  275. checkName,
  276. $formatDate,
  277. floatFormat,
  278. pageTo,
  279. isLogin,
  280. getCheckLogin,
  281. numberFormat
  282. };