tool.js 7.3 KB

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