tool.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // import errorCode from './errorCode'
  2. // import baseInfo from './baseInfo'
  3. // import {PRICE_IS_ROUND,SERVER_API_HTTP_TYPE,SERVER_API_DOMAIN,CDN_BASE_URL} from './config'
  4. import usersInfo from '@/utils/usersInfo'
  5. import errorCode from 'core-js/internals/internal-state'
  6. const tool = {
  7. /**
  8. * 设置JS存在客户端的Storage值
  9. * @param key
  10. * @param value
  11. */
  12. setStorage(key, value) {
  13. localStorage.setItem(key, value)
  14. },
  15. /**
  16. * 获取Storage值
  17. * @param key
  18. * @returns {string | null}
  19. */
  20. getStorage(key) {
  21. return localStorage.getItem(key)
  22. },
  23. /**
  24. * 移除Storage值
  25. * @param key
  26. */
  27. removeStorage(key) {
  28. localStorage.removeItem(key)
  29. },
  30. /**
  31. * 获取当前时间戳(精确到秒)
  32. * @returns {number}
  33. */
  34. getTimestamp(date = null) {
  35. const days = usersInfo.daysDiff()
  36. let dateObj
  37. if (date !== null) {
  38. dateObj = new Date(date)
  39. } else {
  40. dateObj = new Date()
  41. }
  42. return +Math.round(dateObj.getTime() / 1000 + (days * 86400))
  43. },
  44. formatDate(timestamp, withTime = true) {
  45. const newDate = new Date()
  46. timestamp = parseInt(timestamp)
  47. if (timestamp) {
  48. newDate.setTime(timestamp * 1000)
  49. } else {
  50. return ''
  51. }
  52. const Y = newDate.getFullYear() + '-'
  53. const M = (newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1) + '-'
  54. const D = (newDate.getDate() < 10 ? '0' + (newDate.getDate()) : newDate.getDate()) + ' '
  55. const h = (newDate.getHours() < 10 ? '0' + newDate.getHours() : newDate.getHours()) + ':'
  56. const m = (newDate.getMinutes() < 10 ? '0' + newDate.getMinutes() : newDate.getMinutes()) + ':'
  57. const s = (newDate.getSeconds() < 10 ? '0' + newDate.getSeconds() : newDate.getSeconds())
  58. if (withTime) return Y + M + D + h + m + s
  59. return Y + M + D
  60. },
  61. /**
  62. * 处理错误结果
  63. * @param error
  64. * @returns {{message: string, todo: *}}
  65. */
  66. errorHandle(error) {
  67. let message = ''
  68. let status = 0
  69. let todo
  70. if (errorCode.has(error)) {
  71. const errorResult = errorCode.get(error)
  72. message = errorResult.message
  73. status = errorResult.status ? errorResult.status : 0
  74. todo = errorResult.todo
  75. } else {
  76. message = error.message
  77. todo = null
  78. status = error.data.status ? error.data.status : 0
  79. }
  80. if (todo || status === 401) {
  81. message = todo ? '未获得授权,请重新登录' : (message === 'Your request was made with invalid credentials.' ? '未获得授权,请重新登录' : message)
  82. usersInfo.logout()
  83. }
  84. if (todo || status === 402) {
  85. message = todo ? '长时间未进行操作,请重新登录' : (message === 'Connection not operated for too long' ? '长时间未进行操作,请重新登录' : message)
  86. usersInfo.logout()
  87. }
  88. return { message, todo, status }
  89. },
  90. /**
  91. * 解析URL地址
  92. * @param url
  93. * var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top');
  94. myURL.file; // = 'index.html'
  95. myURL.hash; // = 'top'
  96. myURL.host; // = 'abc.com'
  97. myURL.query; // = '?id=255&m=hello'
  98. myURL.params; // = Object = { id: 255, m: hello }
  99. myURL.path; // = '/dir/index.html'
  100. myURL.segments; // = Array = ['dir', 'index.html']
  101. myURL.port; // = '8080'
  102. myURL.protocol; // = 'http'
  103. myURL.source; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
  104. * @returns {{source: *, protocol: string, host: string, port: string, query: string, params, file: string | *, hash: string, path: string, relative: string | *, segments: string[]}}
  105. */
  106. parseURL(url) {
  107. const a = document.createElement('a')
  108. a.href = url
  109. return {
  110. source: url,
  111. protocol: a.protocol.replace(':', ''),
  112. host: a.hostname,
  113. port: a.port,
  114. query: a.search,
  115. params: (function() {
  116. const waitUrl = a.hash.replace(/^#\/[\-_a-zA-Z0-9]+\?/, '\?') || a.search
  117. const ret = {}
  118. const seg = waitUrl.replace(/^\?/, '').split('&')
  119. const len = seg.length
  120. let i = 0
  121. let s
  122. for (; i < len; i++) {
  123. if (!seg[i]) {
  124. continue
  125. }
  126. s = seg[i].split('=')
  127. ret[s[0]] = s[1]
  128. }
  129. return ret
  130. })(),
  131. file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
  132. hash: a.hash.replace('#', ''),
  133. path: a.pathname.replace(/^([^\/])/, '/$1'),
  134. relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
  135. segments: a.pathname.replace(/^\//, '').split('/')
  136. }
  137. },
  138. removeFromArr(arr, item) {
  139. for (let i = arr.length - 1; i >= 0; i--) {
  140. if (arr[i] === item) {
  141. arr.splice(i, 1)
  142. return arr
  143. }
  144. }
  145. },
  146. /**
  147. * 是否空对象
  148. * @param obj
  149. * @returns {boolean}
  150. */
  151. isEmptyObject(obj) {
  152. const objArr = Object.keys(obj)
  153. return objArr.length === 0
  154. },
  155. isInArray(arr, value) {
  156. for (const i in arr) {
  157. if (value === arr[i]) {
  158. return true
  159. }
  160. }
  161. return false
  162. },
  163. isString(val) {
  164. return typeof val === 'string' || val instanceof String
  165. },
  166. /**
  167. * 格式化金额数值为两位小数,是否四舍五入
  168. * @param val
  169. * @returns {string}
  170. */
  171. formatPrice(val) {
  172. val = Number.parseFloat(val)
  173. return val.toFixed(2)
  174. },
  175. /**
  176. * 根据状态返回颜色
  177. * @param val
  178. * @returns {string}
  179. */
  180. statusType(val) {
  181. switch (val) {
  182. case '0':
  183. return 'info'
  184. case '1':
  185. return ''
  186. case '2':
  187. return 'danger'
  188. case '3':
  189. return 'warning'
  190. case '4':
  191. return 'success'
  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. // * 拼装图片地址.
  214. // * @param imageUrl
  215. // * @param path
  216. // * @returns {string}
  217. // */
  218. // getLocaleLink(imageUrl, path = '') {
  219. // return imageUrl.indexOf('http') > -1 ? imageUrl : `${process.env.VUE_APP_CDN_API}${path}${imageUrl}`
  220. // },
  221. // 计算商品税额
  222. calculateTax(amount, taxRate, count = 1) {
  223. const taxAmount = (amount - amount / (1 + taxRate / 100)) * count
  224. return Math.round(taxAmount * 100) / 100
  225. },
  226. // 计算商品BV
  227. calculateBV(amount, count = 1) {
  228. return Math.round(amount * count)
  229. },
  230. /**
  231. * 拼装图片
  232. * @param imageUrl 图片
  233. * @param path 路径
  234. * @returns {string}
  235. */
  236. getArImage(imageUrl, path = null) {
  237. return process.env.VUE_APP_CDN_API + `/${path}/${imageUrl}`
  238. },
  239. getEmpLv(id) {
  240. // return id.length > 0 ? getBaseInfo().empLevels : 'No Rank';
  241. },
  242. /**
  243. * 向地址来看
  244. * @param paramName
  245. * @param value
  246. */
  247. insertUrlParam(paramName, value) {
  248. if (typeof value === 'object') {
  249. if (tool.isEmptyObject(value)) {
  250. return
  251. }
  252. value = JSON.stringify(value)
  253. }
  254. if (window.location.href.indexOf(paramName) === -1) {
  255. if (window.location.href.indexOf('?') !== -1) {
  256. window.location.href += ('&' + paramName + '=' + value)
  257. } else {
  258. window.location.href += ('?' + paramName + '=' + value)
  259. }
  260. } else {
  261. const searchStr = new RegExp('(\\?|&)(' + paramName + '=)([^&]*)(&|$)')
  262. window.location.href = window.location.href.replace(searchStr, '$1$2' + value + '$4')
  263. }
  264. }
  265. }
  266. export default tool