Newer
Older
KaiFengPC / src / utils / ruoyi.js
@zhangdeliang zhangdeliang on 24 Jun 8 KB update
  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 = typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  99. dateRange = Array.isArray(dateRange) ? dateRange : [];
  100. if (typeof propName === 'undefined') {
  101. search.params['beginTime'] = dateRange[0];
  102. search.params['endTime'] = dateRange[1];
  103. } else {
  104. search.params['begin' + propName] = dateRange[0];
  105. search.params['end' + propName] = dateRange[1];
  106. }
  107. return search;
  108. }
  109. export function formatAddDateRange(params, dateRange, beginTimepropName, endTimepropName) {
  110. let search = Object.assign({}, params);
  111. dateRange = Array.isArray(dateRange) ? dateRange : [];
  112. search[beginTimepropName] = dateRange && dateRange.length > 0 ? dateRange[0] : '';
  113. search[endTimepropName] = dateRange && dateRange.length > 0 ? dateRange[1] : '';
  114. return search;
  115. }
  116. // 回显数据字典
  117. export function selectDictLabel(datas, value) {
  118. if (value === undefined) {
  119. return '';
  120. }
  121. var actions = [];
  122.  
  123. Object.keys(datas).some(key => {
  124. if (datas[key].value == '' + value) {
  125. actions.push(datas[key].label);
  126. return true;
  127. }
  128. });
  129. if (actions.length === 0) {
  130. actions.push(value);
  131. }
  132.  
  133. return actions.join('');
  134. }
  135.  
  136. // 回显数据字典(字符串数组)
  137. export function selectDictLabels(datas, value, separator) {
  138. if (value === undefined || value.length === 0) {
  139. return '';
  140. }
  141. if (Array.isArray(value)) {
  142. value = value.join(',');
  143. }
  144. var actions = [];
  145. var currentSeparator = undefined === separator ? ',' : separator;
  146. var temp = value.split(currentSeparator);
  147. Object.keys(value.split(currentSeparator)).some(val => {
  148. var match = false;
  149. Object.keys(datas).some(key => {
  150. if (datas[key].value == '' + temp[val]) {
  151. actions.push(datas[key].label + currentSeparator);
  152. match = true;
  153. }
  154. });
  155. if (!match) {
  156. actions.push(temp[val] + currentSeparator);
  157. }
  158. });
  159. return actions.join('').substring(0, actions.join('').length - 1);
  160. }
  161.  
  162. // 字符串格式化(%s )
  163. export function sprintf(str) {
  164. var args = arguments,
  165. flag = true,
  166. i = 1;
  167. str = str.replace(/%s/g, function () {
  168. var arg = args[i++];
  169. if (typeof arg === 'undefined') {
  170. flag = false;
  171. return '';
  172. }
  173. return arg;
  174. });
  175. return flag ? str : '';
  176. }
  177.  
  178. // 转换字符串,undefined,null等转化为""
  179. export function parseStrEmpty(str) {
  180. if (!str || str == 'undefined' || str == 'null') {
  181. return '';
  182. }
  183. return str;
  184. }
  185.  
  186. // 数据合并
  187. export function mergeRecursive(source, target) {
  188. for (var p in target) {
  189. try {
  190. if (target[p].constructor == Object) {
  191. source[p] = mergeRecursive(source[p], target[p]);
  192. } else {
  193. source[p] = target[p];
  194. }
  195. } catch (e) {
  196. source[p] = target[p];
  197. }
  198. }
  199. return source;
  200. }
  201.  
  202. /**
  203. * 构造树型结构数据
  204. * @param {*} data 数据源
  205. * @param {*} id id字段 默认 'id'
  206. * @param {*} parentId 父节点字段 默认 'parentId'
  207. * @param {*} children 孩子节点字段 默认 'children'
  208. */
  209. export function handleTree(data, id, parentId, children) {
  210. let config = {
  211. id: id || 'id',
  212. parentId: parentId || 'parentId',
  213. childrenList: children || 'children',
  214. };
  215.  
  216. var childrenListMap = {};
  217. var nodeIds = {};
  218. var tree = [];
  219.  
  220. for (let d of data) {
  221. let parentId = d[config.parentId];
  222. if (childrenListMap[parentId] == null) {
  223. childrenListMap[parentId] = [];
  224. }
  225. nodeIds[d[config.id]] = d;
  226. childrenListMap[parentId].push(d);
  227. }
  228.  
  229. for (let d of data) {
  230. let parentId = d[config.parentId];
  231. if (nodeIds[parentId] == null) {
  232. tree.push(d);
  233. }
  234. }
  235.  
  236. for (let t of tree) {
  237. adaptToChildrenList(t);
  238. }
  239.  
  240. function adaptToChildrenList(o) {
  241. if (childrenListMap[o[config.id]] !== null) {
  242. o[config.childrenList] = childrenListMap[o[config.id]];
  243. }
  244. if (o[config.childrenList]) {
  245. for (let c of o[config.childrenList]) {
  246. adaptToChildrenList(c);
  247. }
  248. }
  249. }
  250. return tree;
  251. }
  252.  
  253. /**
  254. * 参数处理
  255. * @param {*} params 参数
  256. */
  257. export function tansParams(params) {
  258. let result = '';
  259. for (const propName of Object.keys(params)) {
  260. const value = params[propName];
  261. var part = encodeURIComponent(propName) + '=';
  262. if (value !== null && value !== '' && typeof value !== 'undefined') {
  263. if (typeof value === 'object') {
  264. for (const key of Object.keys(value)) {
  265. if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
  266. let params = propName + '[' + key + ']';
  267. var subPart = encodeURIComponent(params) + '=';
  268. result += subPart + encodeURIComponent(value[key]) + '&';
  269. }
  270. }
  271. } else {
  272. result += part + encodeURIComponent(value) + '&';
  273. }
  274. }
  275. }
  276. return result;
  277. }
  278.  
  279. // 返回项目路径
  280. export function getNormalPath(p) {
  281. if (p.length === 0 || !p || p == 'undefined') {
  282. return p;
  283. }
  284. let res = p.replace('//', '/');
  285. if (res[res.length - 1] === '/') {
  286. return res.slice(0, res.length - 1);
  287. }
  288. return res;
  289. }
  290.  
  291. // 验证是否为blob格式
  292. export async function blobValidate(data) {
  293. try {
  294. const text = await data.text();
  295. JSON.parse(text);
  296. return false;
  297. } catch (error) {
  298. return true;
  299. }
  300. }
  301.  
  302. //计算取值
  303. export const getDivisionResult = (a, b) => {
  304. if (!Number(a) || !Number(b)) {
  305. return '--';
  306. }
  307. return `${parseInt(a / b)}%`;
  308. };
  309.  
  310. //guid
  311. export const guid = () => {
  312. const s4 = () =>
  313. Math.floor((1 + Math.random()) * 0x10000)
  314. .toString(16)
  315. .substring(1);
  316. return (() => `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`)();
  317. };
  318.  
  319. // 动态加载图片
  320. export function getImageUrl(picName, folderName) {
  321. return new URL(`../assets/${folderName}/${picName}`, import.meta.url).href;
  322. }
  323. //动态加载天气图标
  324. export function getWeatherImageUrl(picName, folderName) {
  325. return new URL(`../assets/images/${folderName}/${picName}.png`, import.meta.url).href;
  326. }