tool.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import errorCode from './errorCode'
  2. import baseInfo from './baseInfo'
  3. import {PRICE_IS_ROUND} from './config'
  4. import userInfo from "../../../backendEle/src/utils/userInfo";
  5. let tool = {
  6. /**
  7. * 设置JS存在客户端的Storage值
  8. * @param key
  9. * @param value
  10. */
  11. setStorage(key, value) {
  12. localStorage.setItem(key, value)
  13. },
  14. /**
  15. * 获取Storage值
  16. * @param key
  17. * @returns {string | null}
  18. */
  19. getStorage(key) {
  20. return localStorage.getItem(key)
  21. },
  22. /**
  23. * 移除Storage值
  24. * @param key
  25. */
  26. removeStorage(key) {
  27. localStorage.removeItem(key)
  28. },
  29. /**
  30. * 获取当前时间戳(精确到秒)
  31. * @returns {number}
  32. */
  33. getTimestamp(date = null) {
  34. let days = baseInfo.daysDiff()
  35. let dateObj
  36. if (date !== null) {
  37. dateObj = new Date(date)
  38. } else {
  39. dateObj = new Date()
  40. }
  41. return Math.round(dateObj.getTime() / 1000 + (days * 86400))
  42. },
  43. formatDate(timestamp, withTime = true) {
  44. let newDate = new Date()
  45. timestamp = parseInt(timestamp)
  46. if (timestamp) {
  47. newDate.setTime(timestamp * 1000)
  48. } else {
  49. return ''
  50. }
  51. let Y = newDate.getFullYear() + '-'
  52. let M = (newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1) + '-'
  53. let D = (newDate.getDate() < 10 ? '0' + (newDate.getDate()) : newDate.getDate()) + ' '
  54. let h = (newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours()) + ':'
  55. let m = (newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes()) + ':'
  56. let s = (newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds())
  57. if (withTime) return Y + M + D + h + m + s
  58. return Y + M + D
  59. },
  60. /**
  61. * 处理错误结果
  62. * @param error
  63. * @returns {{message: string, todo: *}}
  64. */
  65. errorHandle(error) {
  66. let message = ''
  67. let status = 0
  68. let todo
  69. if (errorCode.has(error)) {
  70. let errorResult = errorCode.get(error)
  71. message = errorResult.message
  72. status = errorResult.status ? errorResult.status : 0
  73. todo = errorResult.todo
  74. } else {
  75. message = error.message
  76. todo = null
  77. status = error.data.status ? error.data.status : 0
  78. }
  79. if (todo || status === 401) {
  80. message = todo ? 'Not authorized, please log in again.' : (message === 'Your request was made with invalid credentials.' ? 'Not authorized, please log in again.' : message)
  81. userInfo.logout()
  82. }
  83. if (todo || status === 402) {
  84. message = todo ? 'No operation has been performed for a long time,please log in again.':(message === 'Connection not operated for too long' ? 'No operation has been performed for a long time,please log in again.' : message) // 长时间未进行操作,请重新登录
  85. userInfo.logout()
  86. }
  87. return {message, todo, status}
  88. },
  89. /**
  90. * 解析URL地址
  91. * @param url
  92. * var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
  93. myURL.file; // = 'index.html'
  94. myURL.hash; // = 'top'
  95. myURL.host; // = 'abc.com'
  96. myURL.query; // = '?id=255&m=hello'
  97. myURL.params; // = Object = { id: 255, m: hello }
  98. myURL.path; // = '/dir/index.html'
  99. myURL.segments; // = Array = ['dir', 'index.html']
  100. myURL.port; // = '8080'
  101. myURL.protocol; // = 'http'
  102. myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
  103. * @returns {{source: *, protocol: string, host: string, port: string, query: string, params, file: string | *, hash: string, path: string, relative: string | *, segments: string[]}}
  104. */
  105. parseURL(url) {
  106. let a = document.createElement('a')
  107. a.href = url
  108. return {
  109. source: url,
  110. protocol: a.protocol.replace(':', ''),
  111. host: a.hostname,
  112. port: a.port,
  113. query: a.search,
  114. params: (function () {
  115. let waitUrl = a.hash.replace(/^#\/[\-_a-zA-Z0-9]+\?/, '\?') || a.search
  116. let ret = {},
  117. seg = waitUrl.replace(/^\?/, '').split('&'),
  118. len = seg.length,
  119. i = 0,
  120. s
  121. for (; i < len; i++) {
  122. if (!seg[i]) {
  123. continue
  124. }
  125. s = seg[i].split('=')
  126. ret[s[0]] = s[1]
  127. }
  128. return ret
  129. })(),
  130. file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
  131. hash: a.hash.replace('#', ''),
  132. path: a.pathname.replace(/^([^\/])/, '/$1'),
  133. relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
  134. segments: a.pathname.replace(/^\//, '').split('/')
  135. }
  136. },
  137. removeFromArr(arr, item) {
  138. for (let i = arr.length - 1; i >= 0; i--) {
  139. if (arr[i] === item) {
  140. arr.splice(i, 1)
  141. return arr
  142. }
  143. }
  144. },
  145. isInArray(arr, value) {
  146. for (let i in arr) {
  147. if (value === arr[i]) {
  148. return true
  149. }
  150. }
  151. return false
  152. },
  153. isString(val) {
  154. return typeof val === 'string' || val instanceof String
  155. },
  156. /**
  157. * 格式化金额数值为两位小数,是否四舍五入
  158. * @param val
  159. * @returns {string}
  160. */
  161. formatPrice(val) {
  162. val = Number.parseFloat(val)
  163. if (PRICE_IS_ROUND) {
  164. return val.toFixed(2)
  165. } else {
  166. val = val.toFixed(3)
  167. return val.substring(0, val.lastIndexOf('.') + 3)
  168. }
  169. },
  170. /**
  171. * 根据状态返回颜色
  172. * @param val
  173. * @returns {string}
  174. */
  175. statusType(val) {
  176. switch (val) {
  177. case '0':
  178. return 'info'
  179. break
  180. case '1':
  181. return ''
  182. break
  183. case '2':
  184. return 'danger'
  185. break
  186. case '3':
  187. return 'warning'
  188. break
  189. case '4':
  190. return 'success'
  191. break
  192. default:
  193. return 'info'
  194. }
  195. },
  196. sum(arr) {//求数组总和
  197. var s = 0;
  198. for (var i=arr.length-1; i>=0; i--) {
  199. s += arr[i];
  200. }
  201. return s;
  202. },
  203. /**
  204. * 获取table显示高度
  205. * @param hasStatusBar
  206. * @returns {number}
  207. */
  208. getTableHeight(hasStatusBar = false) {
  209. if (hasStatusBar) return window.innerHeight - 320
  210. return window.innerHeight - 260
  211. },
  212. // 计算商品税额
  213. calculateTax(amount, taxRate, count = 1) {
  214. let taxAmount = (amount - amount / (1 + taxRate / 100)) * count
  215. return Math.round(taxAmount * 100) / 100
  216. },
  217. }
  218. export default tool