index.js 9.3 KB

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