common.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /**
  2. * 通用js方法封装处理
  3. * Copyright (c) 2019 fs
  4. */
  5. const baseURL = process.env.VUE_APP_BASE_API
  6. export function getAge(strBirthday) {
  7. var returnAge,
  8. strBirthdayArr=strBirthday.split("-"),
  9. birthYear = strBirthdayArr[0],
  10. birthMonth = strBirthdayArr[1],
  11. birthDay = strBirthdayArr[2],
  12. d = new Date(),
  13. nowYear = d.getFullYear(),
  14. nowMonth = d.getMonth() + 1,
  15. nowDay = d.getDate();
  16. if(nowYear == birthYear){
  17. returnAge = 0;//同年 则为0周岁
  18. }
  19. else{
  20. var ageDiff = nowYear - birthYear ; //年之差
  21. if(ageDiff > 0){
  22. if(nowMonth == birthMonth) {
  23. var dayDiff = nowDay - birthDay;//日之差
  24. if(dayDiff < 0) {
  25. returnAge = ageDiff - 1;
  26. }else {
  27. returnAge = ageDiff;
  28. }
  29. }else {
  30. var monthDiff = nowMonth - birthMonth;//月之差
  31. if(monthDiff < 0) {
  32. returnAge = ageDiff - 1;
  33. }
  34. else {
  35. returnAge = ageDiff ;
  36. }
  37. }
  38. }else {
  39. returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
  40. }
  41. }
  42. return returnAge;//返回周岁年龄
  43. }
  44. // 日期格式化
  45. export function parseTime(time, pattern) {
  46. if (arguments.length === 0 || !time) {
  47. return null
  48. }
  49. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  50. let date
  51. if (typeof time === 'object') {
  52. date = time
  53. } else {
  54. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  55. time = parseInt(time)
  56. } else if (typeof time === 'string') {
  57. time = time.replace(new RegExp(/-/gm), '/');
  58. }
  59. if ((typeof time === 'number') && (time.toString().length === 10)) {
  60. time = time * 1000
  61. }
  62. date = new Date(time)
  63. }
  64. const formatObj = {
  65. y: date.getFullYear(),
  66. m: date.getMonth() + 1,
  67. d: date.getDate(),
  68. h: date.getHours(),
  69. i: date.getMinutes(),
  70. s: date.getSeconds(),
  71. a: date.getDay()
  72. }
  73. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  74. let value = formatObj[key]
  75. // Note: getDay() returns 0 on Sunday
  76. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  77. if (result.length > 0 && value < 10) {
  78. value = '0' + value
  79. }
  80. return value || 0
  81. })
  82. return time_str
  83. }
  84. // 表单重置
  85. export function resetForm(refName) {
  86. if (this.$refs[refName]) {
  87. this.$refs[refName].resetFields();
  88. }
  89. }
  90. // 添加日期范围
  91. export function addDateRange(params, dateRange) {
  92. var search = params;
  93. search.beginTime = "";
  94. search.endTime = "";
  95. if (null != dateRange && '' != dateRange) {
  96. search.beginTime = this.dateRange[0];
  97. search.endTime = this.dateRange[1];
  98. }
  99. return search;
  100. }
  101. // 回显数据字典
  102. export function selectDictLabel(datas, value) {
  103. var actions = [];
  104. Object.keys(datas).some((key) => {
  105. if (datas[key].dictValue == ('' + value)) {
  106. actions.push(datas[key].dictLabel);
  107. return true;
  108. }
  109. })
  110. return actions.join('');
  111. }
  112. // 回显数据字典(字符串数组)
  113. export function selectDictLabels(datas, value, separator) {
  114. var actions = [];
  115. var currentSeparator = undefined === separator ? "," : separator;
  116. var temp = value.split(currentSeparator);
  117. Object.keys(value.split(currentSeparator)).some((val) => {
  118. Object.keys(datas).some((key) => {
  119. if (datas[key].dictValue == ('' + temp[val])) {
  120. actions.push(datas[key].dictLabel + currentSeparator);
  121. }
  122. })
  123. })
  124. return actions.join('').substring(0, actions.join('').length - 1);
  125. }
  126. // 通用下载方法
  127. export function download(fileName) {
  128. window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true;
  129. }
  130. // 字符串格式化(%s )
  131. export function sprintf(str) {
  132. var args = arguments, flag = true, i = 1;
  133. str = str.replace(/%s/g, function () {
  134. var arg = args[i++];
  135. if (typeof arg === 'undefined') {
  136. flag = false;
  137. return '';
  138. }
  139. return arg;
  140. });
  141. return flag ? str : '';
  142. }
  143. // 转换字符串,undefined,null等转化为""
  144. export function praseStrEmpty(str) {
  145. if (!str || str == "undefined" || str == "null") {
  146. return "";
  147. }
  148. return str;
  149. }
  150. /**
  151. * 构造树型结构数据
  152. * @param {*} data 数据源
  153. * @param {*} id id字段 默认 'id'
  154. * @param {*} parentId 父节点字段 默认 'parentId'
  155. * @param {*} children 孩子节点字段 默认 'children'
  156. * @param {*} rootId 根Id 默认 0
  157. */
  158. export function handleTree(data, id, parentId, children, rootId) {
  159. id = id || 'id'
  160. parentId = parentId || 'parentId'
  161. children = children || 'children'
  162. rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0
  163. //对源数据深度克隆
  164. const cloneData = JSON.parse(JSON.stringify(data))
  165. //循环所有项
  166. const treeData = cloneData.filter(father => {
  167. let branchArr = cloneData.filter(child => {
  168. //返回每一项的子级数组
  169. return father[id] === child[parentId]
  170. });
  171. branchArr.length > 0 ? father.children = branchArr : '';
  172. //返回第一层
  173. return father[parentId] === rootId;
  174. });
  175. return treeData != '' ? treeData : data;
  176. }
  177. export function dateFormat(fmt, date) {
  178. let ret="";
  179. date=new Date(date);
  180. const opt = {
  181. 'Y+': date.getFullYear().toString(), // 年
  182. 'm+': (date.getMonth() + 1).toString(), // 月
  183. 'd+': date.getDate().toString(), // 日
  184. 'H+': date.getHours().toString(), // 时
  185. 'M+': date.getMinutes().toString(), // 分
  186. 'S+': date.getSeconds().toString() // 秒
  187. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  188. }
  189. for (let k in opt) {
  190. ret = new RegExp('(' + k + ')').exec(fmt)
  191. if (ret) {
  192. fmt = fmt.replace(
  193. ret[1],
  194. ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
  195. )
  196. }
  197. }
  198. return fmt
  199. }
  200. export function formatMoney(s,dot) {
  201. s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(2) + "";
  202. var l = s.split(".")[0].split("").reverse(),
  203. r = s.split(".")[1];
  204. var t = "";
  205. for(var i = 0; i < l.length; i ++ ) {
  206. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? dot : "");
  207. }
  208. return t.split("").reverse().join("") + "." + r;
  209. }
  210. export function parseArr(str) {
  211. if(str==null||str==undefined||str==""){
  212. return []
  213. }
  214. else{
  215. var strs=str.split(",");
  216. var data=[];
  217. strs.forEach(element => {
  218. data.push(process.env.VUE_APP_BASE_API+element)
  219. });
  220. return data;
  221. }
  222. }
  223. export function parsePost(posts) {
  224. var postNames="";
  225. if (posts!=null&&posts.length>0 ) {
  226. posts.forEach(item => {
  227. postNames+=item.postName+",";
  228. })
  229. return postNames.substring(0,postNames.length-1)
  230. }
  231. return postNames;
  232. }
  233. export function formatDate(datetime) {
  234. var date = new Date(datetime);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  235. var year = date.getFullYear(),
  236. month = ("0" + (date.getMonth() + 1)).slice(-2),
  237. sdate = ("0" + date.getDate()).slice(-2),
  238. hour = ("0" + date.getHours()).slice(-2),
  239. minute = ("0" + date.getMinutes()).slice(-2),
  240. second = ("0" + date.getSeconds()).slice(-2);
  241. // 拼接
  242. var result = year + "-"+ month +"-"+ sdate +" "+ hour +":"+ minute +":" + second;
  243. // 返回
  244. return result;
  245. }
  246. export function parsePhoto(str) {
  247. if(str==null||str==undefined||str==""){
  248. return []
  249. }
  250. else{
  251. var strs=str.split(",");
  252. var data=[];
  253. strs.forEach(element => {
  254. data.push(element)
  255. });
  256. return data;
  257. }
  258. }