Newer
Older
urbanLifeline_YanAn / src / utils / ruoyi.js
@zhangqy zhangqy on 3 Oct 8 KB first commit
  1. /**
  2. * 通用js方法封装处理
  3. * Copyright (c) 2019 newfiber
  4. */
  5. /**
  6. * 遍历字典
  7. * @param {String, Number} dic - 目标哦字典
  8. * @param {String} targetField - 需要和树结构里哪个字段比较
  9. * @param {Array} value - 根据此值去树结构里遍历
  10. */
  11. export const findDictObj = (value, targetField, dic) => {
  12. for (let i = 0; i < dic.length; i++) {
  13. if (dic[i][targetField] == value) {
  14. return dic[i];
  15. }
  16. }
  17. return {};
  18. };
  19.  
  20. /**
  21. * 遍历树结构
  22. * @param {String, Number} value - 根据此值去树结构里遍历
  23. * @param {String} targetField - 需要和树结构里哪个字段比较
  24. * @param {Array} arr - 目标树结构
  25. */
  26. export function findTreeItem(value, targetField, arr) {
  27. for (let i = 0; i < arr.length; i++) {
  28. let item = arr[i];
  29. if (item[targetField] === value) {
  30. return item;
  31. } else {
  32. if (item.children && item.children.length > 0) {
  33. let res = findTreeItem(value, targetField, item.children);
  34. if (res) {
  35. return res;
  36. }
  37. }
  38. }
  39. }
  40. }
  41.  
  42. // 日期格式化
  43. export function parseTime(time, pattern) {
  44. if (arguments.length === 0 || !time) {
  45. return null;
  46. }
  47. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  48. let date;
  49. if (typeof time === 'object') {
  50. date = time;
  51. } else {
  52. if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
  53. time = parseInt(time);
  54. } else if (typeof time === 'string') {
  55. time = time
  56. .replace(new RegExp(/-/gm), '/')
  57. .replace('T', ' ')
  58. .replace(new RegExp(/\.[\d]{3}/gm), '');
  59. }
  60. if (typeof time === 'number' && time.toString().length === 10) {
  61. time = time * 1000;
  62. }
  63. date = new Date(time);
  64. }
  65. const formatObj = {
  66. y: date.getFullYear(),
  67. m: date.getMonth() + 1,
  68. d: date.getDate(),
  69. h: date.getHours(),
  70. i: date.getMinutes(),
  71. s: date.getSeconds(),
  72. a: date.getDay(),
  73. };
  74. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  75. let value = formatObj[key];
  76. // Note: getDay() returns 0 on Sunday
  77. if (key === 'a') {
  78. return ['日', '一', '二', '三', '四', '五', '六'][value];
  79. }
  80. if (result.length > 0 && value < 10) {
  81. value = '0' + value;
  82. }
  83. return value || 0;
  84. });
  85. return time_str;
  86. }
  87.  
  88. // 表单重置
  89. export function resetForm(refName) {
  90. if (this.$refs[refName]) {
  91. this.$refs[refName].resetFields();
  92. }
  93. }
  94.  
  95. // 添加日期范围
  96. export function addDateRange(params, dateRange, propName) {
  97. let search = params;
  98. search.params =
  99. typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  100. dateRange = Array.isArray(dateRange) ? dateRange : [];
  101. if (typeof propName === 'undefined') {
  102. search.params['beginTime'] = dateRange[0];
  103. search.params['endTime'] = dateRange[1];
  104. } else {
  105. search.params['begin' + propName] = dateRange[0];
  106. search.params['end' + propName] = dateRange[1];
  107. }
  108. return search;
  109. }
  110. export function formatAddDateRange(params, dateRange, beginTimepropName, endTimepropName) {
  111. let search = Object.assign({}, params);
  112. dateRange = Array.isArray(dateRange) ? dateRange : [];
  113. search[beginTimepropName] = dateRange && dateRange.length > 0 ? dateRange[0] : '';
  114. search[endTimepropName] = dateRange && dateRange.length > 0 ? dateRange[1] : '';
  115. return search;
  116. }
  117. // 回显数据字典
  118. export function selectDictLabel(datas, value) {
  119. if (value === undefined) {
  120. return '';
  121. }
  122. var actions = [];
  123.  
  124. Object.keys(datas).some(key => {
  125. if (datas[key].value == '' + value) {
  126. actions.push(datas[key].label);
  127. return true;
  128. }
  129. });
  130. if (actions.length === 0) {
  131. actions.push(value);
  132. }
  133.  
  134. return actions.join('');
  135. }
  136.  
  137. // 回显数据字典(字符串数组)
  138. export function selectDictLabels(datas, value, separator) {
  139. if (value === undefined || value.length === 0) {
  140. return '';
  141. }
  142. if (Array.isArray(value)) {
  143. value = value.join(',');
  144. }
  145. var actions = [];
  146. var currentSeparator = undefined === separator ? ',' : separator;
  147. var temp = value.split(currentSeparator);
  148. Object.keys(value.split(currentSeparator)).some(val => {
  149. var match = false;
  150. Object.keys(datas).some(key => {
  151. if (datas[key].value == '' + temp[val]) {
  152. actions.push(datas[key].label + currentSeparator);
  153. match = true;
  154. }
  155. });
  156. if (!match) {
  157. actions.push(temp[val] + currentSeparator);
  158. }
  159. });
  160. return actions.join('').substring(0, actions.join('').length - 1);
  161. }
  162.  
  163. // 字符串格式化(%s )
  164. export function sprintf(str) {
  165. var args = arguments,
  166. flag = true,
  167. i = 1;
  168. str = str.replace(/%s/g, function () {
  169. var arg = args[i++];
  170. if (typeof arg === 'undefined') {
  171. flag = false;
  172. return '';
  173. }
  174. return arg;
  175. });
  176. return flag ? str : '';
  177. }
  178.  
  179. // 转换字符串,undefined,null等转化为""
  180. export function parseStrEmpty(str) {
  181. if (!str || str == 'undefined' || str == 'null') {
  182. return '';
  183. }
  184. return str;
  185. }
  186.  
  187. // 数据合并
  188. export function mergeRecursive(source, target) {
  189. for (var p in target) {
  190. try {
  191. if (target[p].constructor == Object) {
  192. source[p] = mergeRecursive(source[p], target[p]);
  193. } else {
  194. source[p] = target[p];
  195. }
  196. } catch (e) {
  197. source[p] = target[p];
  198. }
  199. }
  200. return source;
  201. }
  202.  
  203. /**
  204. * 构造树型结构数据
  205. * @param {*} data 数据源
  206. * @param {*} id id字段 默认 'id'
  207. * @param {*} parentId 父节点字段 默认 'parentId'
  208. * @param {*} children 孩子节点字段 默认 'children'
  209. */
  210. export function handleTree(data, id, parentId, children) {
  211. let config = {
  212. id: id || 'id',
  213. parentId: parentId || 'parentId',
  214. childrenList: children || 'children',
  215. };
  216.  
  217. var childrenListMap = {};
  218. var nodeIds = {};
  219. var tree = [];
  220.  
  221. for (let d of data) {
  222. let parentId = d[config.parentId];
  223. if (childrenListMap[parentId] == null) {
  224. childrenListMap[parentId] = [];
  225. }
  226. nodeIds[d[config.id]] = d;
  227. childrenListMap[parentId].push(d);
  228. }
  229.  
  230. for (let d of data) {
  231. let parentId = d[config.parentId];
  232. if (nodeIds[parentId] == null) {
  233. tree.push(d);
  234. }
  235. }
  236.  
  237. for (let t of tree) {
  238. adaptToChildrenList(t);
  239. }
  240.  
  241. function adaptToChildrenList(o) {
  242. if (childrenListMap[o[config.id]] !== null) {
  243. o[config.childrenList] = childrenListMap[o[config.id]];
  244. }
  245. if (o[config.childrenList]) {
  246. for (let c of o[config.childrenList]) {
  247. adaptToChildrenList(c);
  248. }
  249. }
  250. }
  251. return tree;
  252. }
  253.  
  254. /**
  255. * 参数处理
  256. * @param {*} params 参数
  257. */
  258. export function tansParams(params) {
  259. let result = '';
  260. for (const propName of Object.keys(params)) {
  261. const value = params[propName];
  262. var part = encodeURIComponent(propName) + '=';
  263. if (value !== null && value !== '' && typeof value !== 'undefined') {
  264. if (typeof value === 'object') {
  265. for (const key of Object.keys(value)) {
  266. if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
  267. let params = propName + '[' + key + ']';
  268. var subPart = encodeURIComponent(params) + '=';
  269. result += subPart + encodeURIComponent(value[key]) + '&';
  270. }
  271. }
  272. } else {
  273. result += part + encodeURIComponent(value) + '&';
  274. }
  275. }
  276. }
  277. return result;
  278. }
  279.  
  280. // 返回项目路径
  281. export function getNormalPath(p) {
  282. if (p.length === 0 || !p || p == 'undefined') {
  283. return p;
  284. }
  285. let res = p.replace('//', '/');
  286. if (res[res.length - 1] === '/') {
  287. return res.slice(0, res.length - 1);
  288. }
  289. return res;
  290. }
  291.  
  292. // 验证是否为blob格式
  293. export async function blobValidate(data) {
  294. try {
  295. const text = await data.text();
  296. JSON.parse(text);
  297. return false;
  298. } catch (error) {
  299. return true;
  300. }
  301. }
  302.  
  303. //计算取值
  304. export const getDivisionResult = (a, b) => {
  305. if (!Number(a) || !Number(b)) {
  306. return '--';
  307. }
  308. return `${parseInt(a / b)}%`;
  309. };
  310.  
  311. //guid
  312. export const guid = () => {
  313. const s4 = () =>
  314. Math.floor((1 + Math.random()) * 0x10000)
  315. .toString(16)
  316. .substring(1);
  317. return (() => `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`)();
  318. };
  319.  
  320. // 动态加载图片
  321. export function getImageUrl(picName, folderName) {
  322. return new URL(`../assets/${folderName}/${picName}`, import.meta.url).href;
  323. }