index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { parseTime } from './ruoyi'
  2. /**
  3. * 表格时间格式化
  4. */
  5. export function formatDate(cellValue) {
  6. if (cellValue == null || cellValue == "") return "";
  7. var date = new Date(cellValue)
  8. var year = date.getFullYear()
  9. var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  10. var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  11. var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  12. var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  13. var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  14. return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  15. }
  16. // 数字格式化
  17. export function rowNum(num) {
  18. if (!num) {
  19. return 0.00;
  20. }
  21. num = num.toLocaleString();
  22. if (num.indexOf(".") == -1) {
  23. num = num + ".00";
  24. } else {
  25. var parts = num.split('.');
  26. var lastPart = parts[parts.length - 1];
  27. if (lastPart.length < 2) {
  28. num = num + "0";
  29. }
  30. }
  31. return num;
  32. }
  33. // 数字格式化
  34. export function numberToCurrencyNo(value) {
  35. if (!value) return 0;
  36. // 获取整数部分
  37. const intPart = Math.trunc(value);
  38. // 整数部分处理,增加,
  39. const intPartFormat = intPart
  40. .toString()
  41. .replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
  42. // 预定义小数部分
  43. let floatPart = "";
  44. // 将数值截取为小数部分和整数部分
  45. const valueArray = value.toString().split(".");
  46. if (valueArray.length === 2) {
  47. // 有小数部分
  48. floatPart = valueArray[1].toString(); // 取得小数部分
  49. console.log("整数部分", intPartFormat + "." + floatPart, "小数部分");
  50. return intPartFormat + "." + floatPart;
  51. }
  52. return intPartFormat + floatPart;
  53. }
  54. /**
  55. * @param {number} time
  56. * @param {string} option
  57. * @returns {string}
  58. */
  59. export function formatTime(time, option) {
  60. if (('' + time).length === 10) {
  61. time = parseInt(time) * 1000
  62. } else {
  63. time = +time
  64. }
  65. const d = new Date(time)
  66. const now = Date.now()
  67. const diff = (now - d) / 1000
  68. if (diff < 30) {
  69. return '刚刚'
  70. } else if (diff < 3600) {
  71. // less 1 hour
  72. return Math.ceil(diff / 60) + '分钟前'
  73. } else if (diff < 3600 * 24) {
  74. return Math.ceil(diff / 3600) + '小时前'
  75. } else if (diff < 3600 * 24 * 2) {
  76. return '1天前'
  77. }
  78. if (option) {
  79. return parseTime(time, option)
  80. } else {
  81. return (
  82. d.getMonth() +
  83. 1 +
  84. '月' +
  85. d.getDate() +
  86. '日' +
  87. d.getHours() +
  88. '时' +
  89. d.getMinutes() +
  90. '分'
  91. )
  92. }
  93. }
  94. /**
  95. * @param {string} url
  96. * @returns {Object}
  97. */
  98. export function getQueryObject(url) {
  99. url = url == null ? window.location.href : url
  100. const search = url.substring(url.lastIndexOf('?') + 1)
  101. const obj = {}
  102. const reg = /([^?&=]+)=([^?&=]*)/g
  103. search.replace(reg, (rs, $1, $2) => {
  104. const name = decodeURIComponent($1)
  105. let val = decodeURIComponent($2)
  106. val = String(val)
  107. obj[name] = val
  108. return rs
  109. })
  110. return obj
  111. }
  112. /**
  113. * @param {string} input value
  114. * @returns {number} output value
  115. */
  116. export function byteLength(str) {
  117. // returns the byte length of an utf8 string
  118. let s = str.length
  119. for (var i = str.length - 1; i >= 0; i--) {
  120. const code = str.charCodeAt(i)
  121. if (code > 0x7f && code <= 0x7ff) s++
  122. else if (code > 0x7ff && code <= 0xffff) s += 2
  123. if (code >= 0xDC00 && code <= 0xDFFF) i--
  124. }
  125. return s
  126. }
  127. /**
  128. * @param {Array} actual
  129. * @returns {Array}
  130. */
  131. export function cleanArray(actual) {
  132. const newArray = []
  133. for (let i = 0; i < actual.length; i++) {
  134. if (actual[i]) {
  135. newArray.push(actual[i])
  136. }
  137. }
  138. return newArray
  139. }
  140. /**
  141. * @param {Object} json
  142. * @returns {Array}
  143. */
  144. export function param(json) {
  145. if (!json) return ''
  146. return cleanArray(
  147. Object.keys(json).map(key => {
  148. if (json[key] === undefined) return ''
  149. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  150. })
  151. ).join('&')
  152. }
  153. /**
  154. * @param {string} url
  155. * @returns {Object}
  156. */
  157. export function param2Obj(url) {
  158. const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  159. if (!search) {
  160. return {}
  161. }
  162. const obj = {}
  163. const searchArr = search.split('&')
  164. searchArr.forEach(v => {
  165. const index = v.indexOf('=')
  166. if (index !== -1) {
  167. const name = v.substring(0, index)
  168. const val = v.substring(index + 1, v.length)
  169. obj[name] = val
  170. }
  171. })
  172. return obj
  173. }
  174. /**
  175. * @param {string} val
  176. * @returns {string}
  177. */
  178. export function html2Text(val) {
  179. const div = document.createElement('div')
  180. div.innerHTML = val
  181. return div.textContent || div.innerText
  182. }
  183. /**
  184. * Merges two objects, giving the last one precedence
  185. * @param {Object} target
  186. * @param {(Object|Array)} source
  187. * @returns {Object}
  188. */
  189. export function objectMerge(target, source) {
  190. if (typeof target !== 'object') {
  191. target = {}
  192. }
  193. if (Array.isArray(source)) {
  194. return source.slice()
  195. }
  196. Object.keys(source).forEach(property => {
  197. const sourceProperty = source[property]
  198. if (typeof sourceProperty === 'object') {
  199. target[property] = objectMerge(target[property], sourceProperty)
  200. } else {
  201. target[property] = sourceProperty
  202. }
  203. })
  204. return target
  205. }
  206. /**
  207. * @param {HTMLElement} element
  208. * @param {string} className
  209. */
  210. export function toggleClass(element, className) {
  211. if (!element || !className) {
  212. return
  213. }
  214. let classString = element.className
  215. const nameIndex = classString.indexOf(className)
  216. if (nameIndex === -1) {
  217. classString += '' + className
  218. } else {
  219. classString =
  220. classString.substr(0, nameIndex) +
  221. classString.substr(nameIndex + className.length)
  222. }
  223. element.className = classString
  224. }
  225. /**
  226. * @param {string} type
  227. * @returns {Date}
  228. */
  229. export function getTime(type) {
  230. if (type === 'start') {
  231. return new Date().getTime() - 3600 * 1000 * 24 * 90
  232. } else {
  233. return new Date(new Date().toDateString())
  234. }
  235. }
  236. /**
  237. * @param {Function} func
  238. * @param {number} wait
  239. * @param {boolean} immediate
  240. * @return {*}
  241. */
  242. export function debounce(func, wait, immediate) {
  243. let timeout, args, context, timestamp, result
  244. const later = function () {
  245. // 据上一次触发时间间隔
  246. const last = +new Date() - timestamp
  247. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  248. if (last < wait && last > 0) {
  249. timeout = setTimeout(later, wait - last)
  250. } else {
  251. timeout = null
  252. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  253. if (!immediate) {
  254. result = func.apply(context, args)
  255. if (!timeout) context = args = null
  256. }
  257. }
  258. }
  259. return function (...args) {
  260. context = this
  261. timestamp = +new Date()
  262. const callNow = immediate && !timeout
  263. // 如果延时不存在,重新设定延时
  264. if (!timeout) timeout = setTimeout(later, wait)
  265. if (callNow) {
  266. result = func.apply(context, args)
  267. context = args = null
  268. }
  269. return result
  270. }
  271. }
  272. /**
  273. * This is just a simple version of deep copy
  274. * Has a lot of edge cases bug
  275. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  276. * @param {Object} source
  277. * @returns {Object}
  278. */
  279. export function deepClone(source) {
  280. if (!source && typeof source !== 'object') {
  281. throw new Error('error arguments', 'deepClone')
  282. }
  283. const targetObj = source.constructor === Array ? [] : {}
  284. Object.keys(source).forEach(keys => {
  285. if (source[keys] && typeof source[keys] === 'object') {
  286. targetObj[keys] = deepClone(source[keys])
  287. } else {
  288. targetObj[keys] = source[keys]
  289. }
  290. })
  291. return targetObj
  292. }
  293. /**
  294. * @param {Array} arr
  295. * @returns {Array}
  296. */
  297. export function uniqueArr(arr) {
  298. return Array.from(new Set(arr))
  299. }
  300. /**
  301. * @returns {string}
  302. */
  303. export function createUniqueString() {
  304. const timestamp = +new Date() + ''
  305. const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  306. return (+(randomNum + timestamp)).toString(32)
  307. }
  308. /**
  309. * Check if an element has a class
  310. * @param {HTMLElement} elm
  311. * @param {string} cls
  312. * @returns {boolean}
  313. */
  314. export function hasClass(ele, cls) {
  315. return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  316. }
  317. /**
  318. * Add class to element
  319. * @param {HTMLElement} elm
  320. * @param {string} cls
  321. */
  322. export function addClass(ele, cls) {
  323. if (!hasClass(ele, cls)) ele.className += ' ' + cls
  324. }
  325. /**
  326. * Remove class from element
  327. * @param {HTMLElement} elm
  328. * @param {string} cls
  329. */
  330. export function removeClass(ele, cls) {
  331. if (hasClass(ele, cls)) {
  332. const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
  333. ele.className = ele.className.replace(reg, ' ')
  334. }
  335. }
  336. export function makeMap(str, expectsLowerCase) {
  337. const map = Object.create(null)
  338. const list = str.split(',')
  339. for (let i = 0; i < list.length; i++) {
  340. map[list[i]] = true
  341. }
  342. return expectsLowerCase
  343. ? val => map[val.toLowerCase()]
  344. : val => map[val]
  345. }
  346. export const exportDefault = 'export default '
  347. export const beautifierConf = {
  348. html: {
  349. indent_size: '2',
  350. indent_char: ' ',
  351. max_preserve_newlines: '-1',
  352. preserve_newlines: false,
  353. keep_array_indentation: false,
  354. break_chained_methods: false,
  355. indent_scripts: 'separate',
  356. brace_style: 'end-expand',
  357. space_before_conditional: true,
  358. unescape_strings: false,
  359. jslint_happy: false,
  360. end_with_newline: true,
  361. wrap_line_length: '110',
  362. indent_inner_html: true,
  363. comma_first: false,
  364. e4x: true,
  365. indent_empty_lines: true
  366. },
  367. js: {
  368. indent_size: '2',
  369. indent_char: ' ',
  370. max_preserve_newlines: '-1',
  371. preserve_newlines: false,
  372. keep_array_indentation: false,
  373. break_chained_methods: false,
  374. indent_scripts: 'normal',
  375. brace_style: 'end-expand',
  376. space_before_conditional: true,
  377. unescape_strings: false,
  378. jslint_happy: true,
  379. end_with_newline: true,
  380. wrap_line_length: '110',
  381. indent_inner_html: true,
  382. comma_first: false,
  383. e4x: true,
  384. indent_empty_lines: true
  385. }
  386. }
  387. // 首字母大小
  388. export function titleCase(str) {
  389. return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
  390. }
  391. // 下划转驼峰
  392. export function camelCase(str) {
  393. return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
  394. }
  395. export function isNumberStr(str) {
  396. return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
  397. }