utils.js 5.9 KB

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