Rap 原分销系统代码Web
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

389 satır
8.8KB

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