utils.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /**
  2. * 判断对象类型
  3. * @param {*} obj 对象
  4. */
  5. export function objTypeOf(obj) {
  6. const toString = Object.prototype.toString;
  7. const map = {
  8. "[object Boolean]": "boolean",
  9. "[object Number]": "number",
  10. "[object String]": "string",
  11. "[object Function]": "function",
  12. "[object Array]": "array",
  13. "[object Date]": "date",
  14. "[object RegExp]": "regExp",
  15. "[object Undefined]": "undefined",
  16. "[object Null]": "null",
  17. "[object Object]": "object",
  18. "[object Blob]": "blob",
  19. };
  20. return map[toString.call(obj)];
  21. }
  22. /**
  23. * 深拷贝
  24. * @param {Object/Array} data 需要拷贝的数据
  25. */
  26. export function deepCopy(data) {
  27. return JSON.parse(JSON.stringify(data));
  28. }
  29. /**
  30. * 将目标对象中有的属性值与源对象中的属性值合并
  31. * @param {Object} target 目标对象
  32. * @param {Object} sources 源对象
  33. */
  34. export function objAssign(target, sources) {
  35. let targ = { ...target };
  36. for (let k in targ) {
  37. targ[k] = Object.prototype.hasOwnProperty.call(sources, k)
  38. ? sources[k]
  39. : targ[k];
  40. }
  41. return targ;
  42. }
  43. /**
  44. * 文件流下载
  45. * @param {Object} option 文件下载设置
  46. */
  47. export function download(option) {
  48. let defOpt = {
  49. type: "get",
  50. url: "",
  51. data: "",
  52. fileName: "",
  53. header: "",
  54. };
  55. let opt = objAssign(defOpt, option);
  56. return new Promise((resolve, reject) => {
  57. let xhr = new XMLHttpRequest();
  58. xhr.open(opt.type.toUpperCase(), opt.url, true);
  59. xhr.responseType = "blob";
  60. // header set
  61. if (opt.header && objTypeOf(opt.header) === "object") {
  62. for (let key in opt.header) {
  63. xhr.setRequestHeader(key, opt.header[key]);
  64. }
  65. }
  66. xhr.onload = function () {
  67. if (this.readyState === 4 && this.status === 200) {
  68. if (this.response.size < 1024) {
  69. reject("文件不存在!");
  70. return;
  71. }
  72. var blob = this.response;
  73. let pdfUrl = "";
  74. let uRl = window.URL || window.webkitURL;
  75. if (uRl && uRl.createObjectURL) {
  76. pdfUrl = uRl.createObjectURL(blob);
  77. } else {
  78. reject("浏览器不兼容!");
  79. }
  80. let a = document.createElement("a");
  81. a.download = opt.fileName;
  82. a.href = pdfUrl;
  83. document.body.appendChild(a);
  84. a.click();
  85. a.parentNode.removeChild(a);
  86. resolve(true);
  87. } else {
  88. reject("请求错误!");
  89. }
  90. };
  91. if (opt.type.toUpperCase() === "POST") {
  92. let fromData = new FormData();
  93. for (let key in opt.data) {
  94. fromData.append(key, opt.data[key]);
  95. }
  96. xhr.send(fromData);
  97. } else {
  98. xhr.send();
  99. }
  100. });
  101. }
  102. /**
  103. * 获取随机code,默认获取16位
  104. * @param {Number} len 推荐8的倍数
  105. *
  106. */
  107. export function randomCode(len = 16) {
  108. if (len <= 0) return;
  109. let steps = Math.ceil(len / 8);
  110. let stepNums = [];
  111. for (let i = 0; i < steps; i++) {
  112. let ranNum = Math.random().toString(32).slice(-8);
  113. stepNums.push(ranNum);
  114. }
  115. return stepNums.join("");
  116. }
  117. /**
  118. *
  119. * @param {String} format 时间格式
  120. * @param {Date} date 需要格式化的时间对象
  121. */
  122. export function formatDate(format = "YYYY/MM/DD HH:mm:ss", date = new Date()) {
  123. if (objTypeOf(date) !== "date") return;
  124. const options = {
  125. "Y+": date.getFullYear(),
  126. "M+": date.getMonth() + 1,
  127. "D+": date.getDate(),
  128. "H+": date.getHours(),
  129. "m+": date.getMinutes(),
  130. "s+": date.getSeconds(),
  131. };
  132. Object.entries(options).map(([key, val]) => {
  133. if (new RegExp("(" + key + ")").test(format)) {
  134. const zeros = key === "Y+" ? "0000" : "00";
  135. const value = (zeros + val).substr(("" + val).length);
  136. format = format.replace(RegExp.$1, value);
  137. }
  138. });
  139. return format;
  140. }
  141. export function parseTimeRangeDateAndTime(startTime, endTime) {
  142. if (!startTime || !endTime)
  143. return {
  144. date: "",
  145. time: "",
  146. };
  147. const st = formatDate("YYYY-MM-DD HH:mm", new Date(startTime)).split(" ");
  148. const et = formatDate("YYYY-MM-DD HH:mm", new Date(endTime)).split(" ");
  149. return {
  150. date: st[0],
  151. time: `${st[1]}-${et[1]}`,
  152. };
  153. }
  154. /**
  155. * 获取本地时间,格式:年月日时分秒
  156. */
  157. export function localNowDateTime() {
  158. return formatDate("YYYY年MM月DD日HH时mm分ss秒");
  159. }
  160. /**
  161. *
  162. * @param {Number} time 时间戳
  163. */
  164. export function getTimeDatestamp(time) {
  165. const date = formatDate("YYYY-MM-DD HH:mm", new Date(time)).split(" ")[0];
  166. return new Date(`${date} 00:00:00`).getTime();
  167. }
  168. /**
  169. * 清除html标签
  170. * @param {String} str html字符串
  171. */
  172. export function removeHtmlTag(str) {
  173. return str.replace(/<[^>]+>/g, "");
  174. }
  175. /**
  176. * 计算总数
  177. * @param {Array} dataList 需要统计的数组
  178. */
  179. export function calcSum(dataList) {
  180. if (!dataList.length) return 0;
  181. return dataList.reduce(function (total, item) {
  182. return total + item;
  183. }, 0);
  184. }
  185. /** 获取数组最大数 */
  186. export function maxNum(dataList) {
  187. return Math.max.apply(null, dataList);
  188. }
  189. export function isEmptyObject(obj) {
  190. return !Object.keys(obj).length;
  191. }
  192. export function humpToLowLine(a) {
  193. return a
  194. .replace(/([A-Z])/g, "-$1")
  195. .toLowerCase()
  196. .slice(1);
  197. }
  198. export function pickByNotNull(params) {
  199. let nData = {};
  200. Object.entries(params).forEach(([key, val]) => {
  201. if (val === null || val === "null" || val === "") return;
  202. nData[key] = val;
  203. });
  204. return nData;
  205. }
  206. export function autoSubmitForm(url, params) {
  207. const form = document.createElement("form");
  208. form.action = url;
  209. form.method = "post";
  210. Object.entries(params).forEach(([key, val]) => {
  211. const input = document.createElement("input");
  212. input.type = "hidden";
  213. input.name = key;
  214. input.value = val;
  215. form.appendChild(input);
  216. });
  217. document.body.appendChild(form);
  218. form.submit();
  219. }
  220. export function blobToText(blob) {
  221. return new Promise((resolve, reject) => {
  222. const reader = new FileReader();
  223. reader.readAsText(blob, "utf-8");
  224. reader.onload = function () {
  225. resolve(reader.result);
  226. };
  227. reader.onerror = function () {
  228. reject();
  229. };
  230. });
  231. }
  232. export function parseHrefParam(href, paramName = null) {
  233. if (!href) return;
  234. const paramStr = href.split("?")[1];
  235. if (!paramStr) return;
  236. let params = {};
  237. paramStr.split("&").forEach((item) => {
  238. const con = item.split("=");
  239. params[con[0]] = con[1];
  240. });
  241. return paramName ? params[paramName] : params;
  242. }